﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Microsoft.LiveFX.Client;
using System.Net;
using Google.GData.Contacts;
using System.IO.Ports;
using ModemGSM;
using Microsoft.LiveFX.ResourceModel;
using System.Globalization;
using System.Resources;
using PhoneManager.LanguageText;

namespace PhoneManager
{
    public partial class MDIPhoneManager : Form
    {
              
        #region Tray Icon

        Taskbar.SystemTray AppTrayIcon;

        private void CreateTrayMenu()
        {
            object[] objValues = new object[8];
            objValues[0] = Convert.ToString("Resources.SimCardYellow.ico");
            objValues[1] = Convert.ToString("Resources.SimCardYellow1.ico");
            objValues[2] = Convert.ToString("Resources.SimCardYellow2.ico");
            objValues[3] = Convert.ToString("Resources.SimCardYellow3.ico");
            objValues[4] = Convert.ToString("Resources.SimCardYellow4.ico");
            objValues[5] = Convert.ToString("Resources.SimCardYellow5.ico");
            objValues[6] = Convert.ToString("Resources.SimCardYellow6.ico");
            objValues[7] = Convert.ToString("Resources.SimCardYellow7.ico");

            AppTrayIcon = new Taskbar.SystemTray(this.Text, new Icon(GetType(),"Resources.SimCardYellow.ico"), true);
            AppTrayIcon.IntervalAnimation = 200;
            AppTrayIcon.SetIconRange(this.GetType(),objValues);
            AppTrayIcon.SetContextMenuOrStrip(MenuTrayIcon);
            AppTrayIcon.MouseMove += new Taskbar.SystemTray.TrayMouseEventHandler(AppTrayIcon_MouseMove);
        }

        #endregion

        #region Dispose

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.AppTrayIcon.Dispose();
            }
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion

        #region private var

        private int _PollingIntervalModem = 5;
        private int _PollingIntervalLive = 3600;
        private int _PollingIntervalGoogle = 3600;
        private int _PollingIntervalSMS = 300;

        private Icon iconON = null;
        private Icon iconOFF = null;


        private bool _blink = false;

        #endregion 

        #region Threads

        private Thread AsynIncomingCall;
        private void GetIncomingCall(object Obj)
            {

                Thread.CurrentThread.CurrentUICulture = SharedLib.CultureUI;
            
                if (SharedLib.ModemGSM.IsOpen)
                {
                    FrmIncomingCall frm = new FrmIncomingCall();
                    frm.NameIncomingCall = SharedLib.NameIncomingCall;
                    frm.NumberIncomingCall = SharedLib.NumberIncomingCall;
                    frm.TopMost = true;
                    SharedLib.NameIncomingCall = "";
                    SharedLib.NumberIncomingCall = "";
                    frm.StartPosition = FormStartPosition.CenterScreen;
                    frm.ShowDialog();
                    SharedLib.IsWaitIncomingCall = false;
                    return;
                }
            }

        internal Thread AsyncStatusModem;
        private void GetStatusModem(object Obj)
        {
            Thread.CurrentThread.CurrentUICulture = SharedLib.CultureUI;

            try
            {
                if (SharedLib.ReadInfoModem)
                {
                    switch (SharedLib.ModemGSM.ActiveStatus)
                    {
                        case ActiveStatusEnum.Disconnected:
                        case ActiveStatusEnum.Offline:
                        case ActiveStatusEnum.Error:
                        case ActiveStatusEnum.Unavailable:
                        case ActiveStatusEnum.unknown:
                            {
                                if (this.WindowState != FormWindowState.Minimized && this.Visible)
                                {
                                    ((MDIPhoneManager)Obj).StatusBarMsg.Text = ResourcesText.Tryingopen + " " + SharedLib.ModemConfig.PortTested + " ...";
                                }
                                SharedLib.ModemReOpen();
                            }
                            break;
                    }
                }
                if (SharedLib.ModemGSM.IsOpen)
                {
                    SharedLib.ModemGSM.KeepAlive();
                    if (SharedLib.ModemGSM.Online)
                    {
                        SharedLib.CountOffLine = 0;
                        if (SharedLib.ReadInfoModem)
                        {
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.WordModel + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.ModelCMD)
                            {
                                SharedLib.ModemGSM.ReadPhoneModel();
                            }

                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.PreferredHostOperator + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.PreferredOperatorCMD)
                            {
                                SharedLib.ModemGSM.ReadPreferredOperator();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.LineIdentification + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.LineIdentificationCMD)
                            {
                                SharedLib.ModemGSM.LineIndentificationWrite(true);
                                SharedLib.ModemGSM.ReadIsLineIndentification();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Charsets + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.CharSetsCMD)
                            {
                                SharedLib.ModemGSM.ReadValidCharSets();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD)
                            {
                                SharedLib.ReadPhoneBook();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.CurrentCharset + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.CharSetsCMD)
                            {
                                SharedLib.ModemGSM.ReadCurrentCharSet();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Indicators + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.IndicatorControlCMD)
                            {
                                SharedLib.ModemGSM.ReadIndicators();
                            }
                        }
                        if (!SharedLib.IsConfigedSMS && SharedLib.ModemGSM.ModelATCommands.SMSConfigIndicationsCMD)
                        {
                            SharedLib.IsConfigedSMS = SharedLib.ModemGSM.SMSIndications(1, 1, 0, 1, 1);
                        }
                        if (SharedLib.ReadInfoModem || SharedLib.ReadInfoSMS)
                        {
                            SharedLib.ReadInfoSMS = false;
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.SMSStorages + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.SMSStoragesCMD)
                            {
                                SharedLib.ModemGSM.SMSReadStorages();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.SMSService + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.SMSMessageServiceCMD)
                            {
                                SharedLib.ModemGSM.SMSGetService();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.SMSMessages + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.SMSListMessageCMD)
                            {
                                SharedLib.ModemGSM.SMSListMessagesTextFormat();
                            }
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.SMSFormats + "...");
                            }
                            if (SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD)
                            {
                                SharedLib.ModemGSM.SMSReadExistTextFormat();
                                SharedLib.ModemGSM.SMSReadExistPDUFormat();
                            }
                        }
                        if (SharedLib.ReadInfoModem || SharedLib.ReadInfoLive)
                        {
                            SharedLib.ReadInfoLive = false;
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.LiveContatcs + "...");
                            }
                            ReadContactsLive(true);
                        }
                        if (SharedLib.ReadInfoModem || SharedLib.ReadInfoGoogle)
                        {
                            SharedLib.ReadInfoGoogle = false;
                            if (this.WindowState != FormWindowState.Minimized && this.Visible)
                            {
                                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.GoogleContatcs + "...");
                            }
                            ReadContactsGoogle(true);
                        }

                        if (this.WindowState != FormWindowState.Minimized && this.Visible)
                        {
                            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.SignalQuality + "...");
                        }
                        if (SharedLib.ModemGSM.ModelATCommands.SignalQualityCMD)
                        {
                            SharedLib.ModemGSM.ReadSignalQuality();
                        }
                        if (this.WindowState != FormWindowState.Minimized && this.Visible)
                        {
                            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.BatteryLevel + "...");
                        }
                        if (SharedLib.ModemGSM.ModelATCommands.BatteryLevelCMD)
                        {
                            SharedLib.ModemGSM.ReadBatteryLevel(Properties.Settings.Default.DefaultBatteryMinLevel);
                        }
                        if (this.WindowState != FormWindowState.Minimized && this.Visible)
                        {
                            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.ActiveStatus + "...");
                        }
                        if (SharedLib.ModemGSM.ModelATCommands.ActiveStatusCMD)
                        {
                            SharedLib.ModemGSM.ReadActiveStatus();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SharedLib.MsgErro(ex.Message);
            }
            SharedLib.ReadInfoModem = false;
            if (this.WindowState != FormWindowState.Minimized && this.Visible)
            {
                ((MDIPhoneManager)Obj).StatusBarMsg.Text = "";
            }
        }

        #endregion

        #region private Methods

        private void RefreshStatusModem()
        {
            ShowMenusAndToolbarAction();
            ShowModel();
            ShowToolBarSignal();
            ShowToolBarNameOperator();
            ShowToolBarBatttery();
            ShowToolBarStatus();
            ShowReportCount();
            if (SharedLib.PollingCountGoogle <= 1 || SharedLib.PollingCountLive <= 1)
            {
                ReadContactsGoogle(true);
                ReadContactsLive(true);
                ShowSyncLiveGoogle();
            }
            if (SharedLib.PollingCountSMS <= 1 )
            {
                if (SharedLib.ModemGSM.ModelATCommands.SMSListMessageCMD)
                {
                    SharedLib.ModemGSM.SMSListMessagesTextFormat();
                }
                ShowSMSMessageCount();
            }
        }

        private void ShowAllStatusModem()
        {
            ShowModel();
            ShowModemConfig();
            ShowToolBarStatus();
            ShowToolBarSignal();
            ShowToolBarNameOperator();
            ShowToolBarBatttery();
            ShowMenusAndToolbarAction();
            ShowPhonebookCount();
            ShowSyncLiveGoogle();
            ShowSMSMessageCount();
        }

        private void ShowModel()
        {
            if (SharedLib.ModemGSM.ModelATCommands.ModelCMD)
            {
                StatusBarModel.Text = SharedLib.ModemGSM.Model;
                TrayIconMenuModel.Text = SharedLib.ModemGSM.Model;
            }
            else
            {
                StatusBarModel.Text = ResourcesText.WordModel + " ???";
                TrayIconMenuModel.Text = ResourcesText.WordModel + " ???";
            }
        }

        private void ShowPhonebookCount()
        { 
            int SIM = 0;
            int Phone = 0;
            if (SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD)
            {
                if (SharedLib.ModemGSM.IsOpen)
                {
                    foreach (PhoneBook item in SharedLib.PhonesBook)
                    {
                        if (item.PhoneIndex != "")
                        {
                            Phone++;
                        }
                        if (item.SIMIndex != "")
                        {
                            SIM++;
                        }
                    }
                }
            }
            string count = SIM.ToString().PadLeft(3, '0') + "~" + Phone.ToString().PadLeft(3, '0');
            toolBarBook.Text = count;
        }

        private void ShowToolBarBatttery()
        {
            if (!SharedLib.ModemGSM.ModelATCommands.BatteryLevelCMD)
            {
                toolBarBattery.Text = "";
                toolBarBattery.Image = Properties.Resources.BatMet0;
            }
            else
            {
                if (!SharedLib.ModemGSM.IsOpen || !SharedLib.ModemGSM.BatteryLevel.HasValue || !SharedLib.ModemGSM.Online)
                {
                    toolBarBattery.Text = "";
                    toolBarBattery.Image = Properties.Resources.BatMet0;
                }
                else
                {
                    toolBarBattery.Text = SharedLib.ModemGSM.BatteryLevel.ToString() + "%";
                    if (SharedLib.ModemGSM.BatteryLevel.Value < 0)
                    {
                        toolBarBattery.Text = "";
                        toolBarBattery.Image = Properties.Resources.BatMet0;
                    }
                    else if (SharedLib.ModemGSM.BatteryLevel.Value <= 10)
                    {
                        toolBarBattery.Image = Properties.Resources.BatMet10;
                    }
                    else if (SharedLib.ModemGSM.BatteryLevel.Value <= 20)
                    {
                        toolBarBattery.Image = Properties.Resources.BatMet20;
                    }
                    else if (SharedLib.ModemGSM.BatteryLevel.Value <= 50)
                    {
                        toolBarBattery.Image = Properties.Resources.BatMet50;
                    }
                    else if (SharedLib.ModemGSM.BatteryLevel.Value <= 80)
                    {
                        toolBarBattery.Image = Properties.Resources.BatMet80;
                    }
                    else
                    {
                        toolBarBattery.Image = Properties.Resources.BatMet100;
                    }
                }
            }
            TrayIconMenuBattery.Text = ResourcesText.WordBattery + " " + toolBarBattery.Text;
            TrayIconMenuBattery.Image = toolBarBattery.Image;
        }

        private void ShowToolBarNameOperator()
        {
            if (SharedLib.ModemGSM.ModelATCommands.PreferredOperatorCMD)
            {
                if (!SharedLib.ModemGSM.IsOpen || !SharedLib.ModemGSM.Online)
                {
                    toolBarSignal.ToolTipText = "";
                }
                else
                {
                    if (String.IsNullOrEmpty(toolBarSignal.ToolTipText))
                    {
                        string ope = SharedLib.ModemGSM.OperName;
                        foreach (var item in Properties.Settings.Default.OperatorProviders)
                        {
                            if (item.Contains(ope))
                            {
                                ope = item.Split(',')[1];
                                break;
                            }
                        }
                        toolBarSignal.ToolTipText = ope;
                    }
                }
            }
            else
            {
                toolBarSignal.ToolTipText = "";
            }
            AppTrayIcon.TrayText = (SharedLib.AssemblyProduct + " " + toolBarSignal.ToolTipText).Trim();
        }

        private void ShowToolBarSignal()
        {
            if (!SharedLib.ModemGSM.ModelATCommands.SignalQualityCMD)
            {
                toolBarSignal.Image = Properties.Resources.Signal0;
                toolBarSignal.Text = "";
                TrayIconMenuSignal.Text = ResourcesText.SignalQuality;
            }
            else
            {
                if (!SharedLib.ModemGSM.IsOpen || !SharedLib.ModemGSM.SignalLevel.HasValue || !SharedLib.ModemGSM.Online)
                {
                    toolBarSignal.Image = Properties.Resources.Signal0;
                    TrayIconMenuSignal.Text = ResourcesText.SignalQuality;
                    toolBarSignal.Text = "";
                }
                else
                {
                    toolBarSignal.Text = ResourcesText.HomeOperLetter;
                    TrayIconMenuSignal.Text = ResourcesText.HomeOper + " " + toolBarSignal.ToolTipText;
                    if (SharedLib.ModemGSM.Indicators != null)
                    {
                        if (SharedLib.ModemGSM.Indicators.Roam.value == 1)
                        {
                            toolBarSignal.Text = ResourcesText.RoamOperLetter;
                            TrayIconMenuSignal.Text = ResourcesText.RoamOper +  " " + toolBarSignal.ToolTipText;
                        }
                    }
                    if (SharedLib.ModemGSM.SignalLevel.Value < 5)
                    {
                        toolBarSignal.Image = Properties.Resources.Signal0;
                    }
                    else if (SharedLib.ModemGSM.SignalLevel.Value <= 10)
                    {
                        toolBarSignal.Image = Properties.Resources.Signal10;
                    }
                    else if (SharedLib.ModemGSM.SignalLevel.Value <= 20)
                    {
                        toolBarSignal.Image = Properties.Resources.Signal20;
                    }
                    else if (SharedLib.ModemGSM.SignalLevel.Value <= 50)
                    {
                        toolBarSignal.Image = Properties.Resources.Signal50;
                    }
                    else if (SharedLib.ModemGSM.SignalLevel.Value <= 80)
                    {
                        toolBarSignal.Image = Properties.Resources.Signal80;
                    }
                    else
                    {
                        toolBarSignal.Image = Properties.Resources.Signal100;
                    }
                }
            }
            TrayIconMenuSignal.Image = toolBarSignal.Image;
        }

        private void ShowToolBarStatus()
        {
            try
            {
                if (!SharedLib.FirstRun && SharedLib.ModemGSM.Online)
                {

                    AppTrayIcon.Icon = iconON;
                }
                else
                {
                    AppTrayIcon.Icon = iconOFF;
                }
            }

            catch { };
            toolBarStatus.ToolTipText = "";
            toolBarStatus.Text = ActiveStatusEnum.Unavailable.ToString();
            toolBarStatus.Image = Properties.Resources.Off;
            toolBarStatus.ForeColor = Color.Red;
            if (SharedLib.ModemGSM.ModelATCommands.ActiveStatusCMD)
            {
                switch (SharedLib.ModemGSM.ActiveStatus)
                {
                    case ActiveStatusEnum.Busy:
                    case ActiveStatusEnum.NoDialtone:
                    case ActiveStatusEnum.NoCarrier:
                    case ActiveStatusEnum.NoAnswer:
                        {
                            toolBarStatus.Image = Properties.Resources.Off;
                            toolBarStatus.ForeColor = Color.Red;
                        }
                        break;
                    case ActiveStatusEnum.Disconnected:
                    case ActiveStatusEnum.asleep:
                    case ActiveStatusEnum.Unavailable:
                        {
                            toolBarStatus.Image = Properties.Resources.Off;
                            toolBarStatus.ForeColor = Color.Red;
                            if (Properties.Settings.Default.HideMenu)
                            {
                                toolBarStatus.ToolTipText = ResourcesText.StatusClick;
                            }
                        }
                        break;
                    case ActiveStatusEnum.Offline:
                        {
                            toolBarStatus.Image = Properties.Resources.On;
                            toolBarStatus.ForeColor = Color.Green;
                            if (Properties.Settings.Default.HideMenu)
                            {
                                toolBarStatus.ToolTipText = ResourcesText.StatusClick;
                            }
                        }
                        break;
                    case ActiveStatusEnum.Error:
                        {
                            toolBarStatus.Image = Properties.Resources.Off;
                            toolBarStatus.ForeColor = Color.Red;
                            if (Properties.Settings.Default.HideMenu)
                            {
                                toolBarStatus.ToolTipText = ResourcesText.StatusClick;
                            }
                        }
                        break;
                    case ActiveStatusEnum.Ready:
                    case ActiveStatusEnum.Ringing:
                    case ActiveStatusEnum.call:
                        {

                            toolBarStatus.Image = Properties.Resources.On;
                            toolBarStatus.ForeColor = Color.Green;
                        }
                        break;
                    default:
                        {
                            toolBarStatus.Image = Properties.Resources.Off;
                            toolBarStatus.ForeColor = Color.Red;
                        }
                        break;
                }
                if (!SharedLib.ModemGSM.IsOpen)
                {
                    toolBarStatus.Text = ActiveStatusEnum.Disconnected.ToString();
                    toolBarStatus.ForeColor = Color.Red;
                    if (Properties.Settings.Default.HideMenu)
                    {
                        toolBarStatus.ToolTipText = ResourcesText.StatusClick;
                    }
                }
                else
                {
                    toolBarStatus.Text = SharedLib.ModemGSM.ActiveStatus.ToString();
                }
            }
            TrayIconMenuStatus.Text = toolBarStatus.Text;
            TrayIconMenuStatus.Image = toolBarStatus.Image;
            TrayIconMenuStatus.ForeColor = toolBarStatus.ForeColor;
            ShowTrayIcon();
        }

        private void ShowMenuToolCharSet()
        {
            if (SharedLib.ModemGSM.ModelATCommands.CharSetsCMD)
            {
                if (menuToolsCharSetGSM.Enabled)
                {
                    menuToolsCharSetGSM.Checked = (menuToolsCharSetGSM.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
                }
                if (menuToolsCharSetHEX.Enabled)
                {
                    menuToolsCharSetHEX.Checked = (menuToolsCharSetHEX.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
                }
                if (menuToolsCharSetIRA.Enabled)
                {
                    menuToolsCharSetIRA.Checked = (menuToolsCharSetIRA.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
                }
                if (menuToolsCharSetISO88591.Enabled)
                {
                    menuToolsCharSetISO88591.Checked = (menuToolsCharSetISO88591.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
                }
                if (menuToolsCharSetP437.Enabled)
                {
                    menuToolsCharSetP437.Checked = (menuToolsCharSetP437.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
                }
                if (menuToolsCharSetUCS2.Enabled)
                {
                    menuToolsCharSetUCS2.Checked = (menuToolsCharSetUCS2.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
                }
            }
        }

        internal void ShowSMSMessageCount()
        {
            int Unread = 0;
            int Read = 0;
            int Unsent = 0;
            int Sent = 0;
            if (SharedLib.ModemGSM.IsOpen)
            {
                if (SharedLib.ModemGSM.ModelATCommands.SMSListMessageCMD)
                {
                    foreach (SMSStorage item in SharedLib.ModemGSM.SMSMessages)
                    {
                        switch (item.Location)
                        {
                            case LocationSMS.UnRead:
                                Unread++;
                                break;
                            case LocationSMS.Read:
                                Read++;
                                break;
                            case LocationSMS.Unsent:
                                Unsent++;
                                break;
                            case LocationSMS.Sent:
                                Sent++;
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            if (!SharedLib.FirstRun && SharedLib.ModemGSM.Online  && SharedLib.ShowOldQtdMsg < 0)
            {
                SharedLib.ShowOldQtdMsg = 0;
                SharedLib.ShowTaskNotif(ResourcesText.WordHave + " " + (Unread + Read).ToString() + " " + ResourcesText.SMSatInboxAnd + " " + (Sent + Unsent).ToString() + " " + ResourcesText.SMSatOutbox);
            }

            if (SharedLib.QtdNewSMSMessage == 0)
            {
                SharedLib.QtdNewSMSMessage = Unread;
            }
            if (SharedLib.ShowOldQtdMsg != SharedLib.QtdNewSMSMessage && SharedLib.QtdNewSMSMessage != 0)
            {
                SharedLib.ShowOldQtdMsg = SharedLib.QtdNewSMSMessage;
                if (!SharedLib.FirstRun && SharedLib.ModemGSM.Online)
                {
                    SharedLib.ShowTaskNotif(ResourcesText.WordHave +  " " + SharedLib.ShowOldQtdMsg.ToString() + " " + ResourcesText.newSMS + "!");
                    object[] objValues = new object[2];
                    objValues[0] = Convert.ToString("Resources.SimCardGreen.ico");
                    objValues[1] = Convert.ToString("Resources.SimCardYellow.ico");
                    AppTrayIcon.SetIconRange(this.GetType(), objValues);
                    AppTrayIcon.StartAnimation();
                }
            }
            string count = (Unread + Read).ToString().PadLeft(3, '0');
            count += " / " + (Unsent > 99 ? 99: Unsent).ToString().PadLeft(2,'0') + "~" + (Sent > 99 ? 99 : Sent).ToString().PadLeft(2,'0');
            toolBarSMS.Text = count;
        }

        internal void ShowReportCount()
        {
            int qtd = 0;
            if (SharedLib.ModemGSM.IsOpen)
            {
                if (SharedLib.ModemGSM.ModelATCommands.SMSSendMessageCMD)
                {
                    qtd = SharedLib.ModemGSM.SMSStatusReport.Count;
                }
            }
            string count = (qtd).ToString().PadLeft(3, '0');
            toolBarSMSRelat.Text = count;
            if (SharedLib.ShowOldQtdRep != qtd && qtd != 0)
            {
                SharedLib.ShowOldQtdMsg = qtd;
                if (!SharedLib.FirstRun && SharedLib.ModemGSM.Online)
                {
                    SharedLib.ShowTaskNotif(ResourcesText.WordHave +  " " + qtd.ToString() + " " + ResourcesText.newSMSReport + "!");
                }
            }
        }

        private void ShowSyncLiveGoogle()
        {
            if (SharedLib.LiveIsLogin)
            {
                toolBarSyncLive.Image = Properties.Resources.live;
                menuSyncLive.Image = Properties.Resources.live;
                menuSyncLiveLoginLogOff.Text = ResourcesText.Logout;
                toolBarSyncLiveLoginLogOff.Text = ResourcesText.Logout;
                menuSyncLivePhone.Enabled = true;
                toolBarSyncLivePhone.Enabled = true;
            }
            else
            {
                toolBarSyncLive.Image = Properties.Resources.liveOff;
                menuSyncLive.Image = Properties.Resources.liveOff;
                menuSyncLiveLoginLogOff.Text = ResourcesText.Login;
                toolBarSyncLiveLoginLogOff.Text = ResourcesText.Login;
                menuSyncLivePhone.Enabled = false;
                toolBarSyncLivePhone.Enabled = false;
            }
            if (SharedLib.GoogleIsLogin)
            {
                toolBarSyncGoogle.Image = Properties.Resources.GOOGLE;
                menuSyncGoogle.Image = Properties.Resources.GOOGLE;
                menuSyncGoogleLoginLogOff.Text = ResourcesText.Logout;
                toolBarSyncGoogleLoginLogOff.Text = ResourcesText.Logout;
                menuSyncGooglePhone.Enabled = true;
                toolBarSyncGooglePhone.Enabled = true;
            }
            else
            {
                toolBarSyncGoogle.Image = Properties.Resources.GOOGLEOff;
                menuSyncGoogle.Image = Properties.Resources.GOOGLEOff;
                menuSyncGoogleLoginLogOff.Text = ResourcesText.Login;
                toolBarSyncGoogleLoginLogOff.Text = ResourcesText.Login;
                menuSyncGooglePhone.Enabled = false;
                toolBarSyncGooglePhone.Enabled = false;
            }
            SharedLib.ShowAtuNewSync = 0;
            if (SharedLib.ModemGSM.IsOpen)
            {
                SharedLib.ShowAtuNewSync = SharedLib.GetQtdNotSyncContacts(); ;
            }
            if (!SharedLib.FirstRun && SharedLib.ModemGSM.Online && SharedLib.ShowoldNewSync != SharedLib.ShowAtuNewSync && SharedLib.ShowAtuNewSync != 0)
            {
                SharedLib.ShowoldNewSync = SharedLib.ShowAtuNewSync;
                if (!SharedLib.FirstRun)
                {
                    SharedLib.ShowTaskNotif(ResourcesText.WordHave + SharedLib.ShowoldNewSync.ToString() + ResourcesText.NewContSync);
                }
            }
            toolbarNewPhoneSync.Text = SharedLib.ShowAtuNewSync.ToString() + ResourcesText.NewContSync;
            toolbarNewPhoneSync.Visible = (SharedLib.ShowAtuNewSync != 0);
        }

        private void ShowMenusAndToolbarAction()
        {
            menuAppConnect.Enabled = !SharedLib.ModemGSM.IsOpen;
            menuAppDisconnect.Enabled = SharedLib.ModemGSM.IsOpen;

            menuPhoneBook.Enabled = SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD && SharedLib.ModemGSM.Online;
            menuBookBackup.Enabled = SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD && SharedLib.ModemGSM.Online;
            menuBookRestore.Enabled = SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD && SharedLib.ModemGSM.Online;

            menuSMS.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD && SharedLib.ModemGSM.Online;
            menuSMSConfig.Visible = SharedLib.ModemGSM.ModelATCommands.SMSStoragesCMD && SharedLib.ModemGSM.Online;
            menuSMSSend.Visible = SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD && SharedLib.ModemGSM.Online;
            menuSMSConfig.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSStoragesCMD && SharedLib.ModemGSM.Online;
            menuSMSSend.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD && SharedLib.ModemGSM.Online;
            menuSMSReport.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSConfigIndicationsCMD && SharedLib.ModemGSM.Online;

            menuPhoneTalk.Enabled = SharedLib.ModemGSM.Online;
            menuPhoneAlarms.Enabled = SharedLib.ModemGSM.ModelATCommands.AlarmCMD && SharedLib.ModemGSM.Online;
            menuSync.Enabled = SharedLib.ModemGSM.IsOpen;
            menuSyncLiveLoginLogOff.Enabled = SharedLib.ModemGSM.IsOpen;
            menuSyncGoogleLoginLogOff.Enabled = SharedLib.ModemGSM.IsOpen;
            menuSyncLive.Enabled = SharedLib.ModemGSM.IsOpen;
            menuSyncGoogle.Enabled = SharedLib.ModemGSM.IsOpen;
            menuSyncDateTime.Enabled = SharedLib.ModemGSM.ModelATCommands.ClockCMD && SharedLib.ModemGSM.Online;
            toolBarSMS.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD && SharedLib.ModemGSM.Online;
            toolBarSMSRelat.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSConfigIndicationsCMD && SharedLib.ModemGSM.Online;

            toolBarTalk.Enabled = SharedLib.ModemGSM.Online;
            toolBarBook.Enabled = SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD && SharedLib.ModemGSM.Online;
            toolBarBookBackup.Enabled = SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD && SharedLib.ModemGSM.Online;
            toolBarBookRestore.Enabled = SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD && SharedLib.ModemGSM.Online;
            toolBarAlarms.Enabled = SharedLib.ModemGSM.ModelATCommands.AlarmCMD && SharedLib.ModemGSM.Online;
            toolBarSyncDateTime.Enabled = SharedLib.ModemGSM.ModelATCommands.ClockCMD && SharedLib.ModemGSM.Online;

            toolBarSyncLiveLoginLogOff.Enabled = SharedLib.ModemGSM.IsOpen;
            toolBarSyncGoogleLoginLogOff.Enabled = SharedLib.ModemGSM.IsOpen;
            toolBarSyncGoogle.Enabled = SharedLib.ModemGSM.IsOpen;
            toolBarSyncLive.Enabled = SharedLib.ModemGSM.IsOpen;

            menuToolsAnalizeModem.Enabled = SharedLib.ModemGSM.IsOpen && SharedLib.ModemGSM.Online;
            
            bool SmsStoOk = false;
            menuCfgSMSReadDeleteSim.Enabled = false;
            menuCfgSMSReadDeletePhone.Enabled = false;
            foreach (var item in SharedLib.ModemGSM.SMSStorages.StoReadDelete)
	        {
                if (item == "SM" && SharedLib.ModemGSM.Online)
                 {
                     menuCfgSMSReadDeleteSim.Enabled = true;
                     SmsStoOk = true;
                 }
                if (item == "ME" && SharedLib.ModemGSM.Online)
                 {
                     menuCfgSMSReadDeletePhone.Enabled = true;
                     SmsStoOk = true;
                 }
            }
            if (menuCfgSMSReadDeleteSim.Enabled == false)
            {
                menuCfgSMSReadDeleteSim.Checked = false;
            }
            else
            {
                menuCfgSMSReadDeleteSim.Checked = Properties.Settings.Default.DefaultSMSReadDelete == "SM";
            }
            if (menuCfgSMSReadDeletePhone.Enabled == false)
            {
                menuCfgSMSReadDeletePhone.Checked = false;
            }
            else
            {
                menuCfgSMSReadDeletePhone.Checked = Properties.Settings.Default.DefaultSMSReadDelete == "ME";
            }

            menuToolsDefaultSet.Enabled = SharedLib.ModemGSM.Online;

            menuCfgSMSWriteSendSim.Enabled = false;
            menuCfgSMSWriteSendPhone.Enabled = false;
            foreach (var item in SharedLib.ModemGSM.SMSStorages.StoWriteSend)
            {
                if (item == "SM" && SharedLib.ModemGSM.Online)
                {
                    menuCfgSMSWriteSendSim.Enabled = true;
                    SmsStoOk = true;
                }
                if (item == "ME" && SharedLib.ModemGSM.Online)
                {
                    menuCfgSMSWriteSendPhone.Enabled = true;
                    SmsStoOk = true;
                }
            }
            if (menuCfgSMSWriteSendSim.Enabled == false)
            {
                menuCfgSMSWriteSendSim.Checked = false;
            }
            else
            {
                menuCfgSMSWriteSendSim.Checked = Properties.Settings.Default.DefaultSMSWriteSend == "SM";
            }
            if (menuCfgSMSWriteSendPhone.Enabled == false)
            {
                menuCfgSMSWriteSendPhone.Checked = false;
            }
            else
            {
                menuCfgSMSWriteSendPhone.Checked = Properties.Settings.Default.DefaultSMSWriteSend == "ME";
            }

            menuCfgSMSReceiverSim.Enabled = false;
            menuCfgSMSReceiverPhone.Enabled = false;
            foreach (var item in SharedLib.ModemGSM.SMSStorages.StoReceiver)
            {
                if (item == "SM" && SharedLib.ModemGSM.Online)
                {
                    menuCfgSMSReceiverSim.Enabled = true;
                    SmsStoOk = true;
                }
                if (item == "ME" && SharedLib.ModemGSM.Online)
                {
                    menuCfgSMSReceiverPhone.Enabled = true;
                    SmsStoOk = true;
                }
            }
            if (menuCfgSMSReceiverSim.Enabled == false)
            {
                menuCfgSMSReceiverSim.Checked = false;
            }
            else
            {
                menuCfgSMSReceiverSim.Checked = Properties.Settings.Default.DefaultSMSReceiver == "SM";
            }
            if (menuCfgSMSReceiverPhone.Enabled == false)
            {
                menuCfgSMSReceiverPhone.Checked = false;
            }
            else
            {
                menuCfgSMSReceiverPhone.Checked = Properties.Settings.Default.DefaultSMSReceiver == "ME";
            }
            menuCfgSMSAllSim.Enabled = SmsStoOk;
            menuCfgSMSAllPhone.Enabled = SmsStoOk;
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (SmsStoOk)
            {
                if (Properties.Settings.Default.DefaultSMSReadDelete == Properties.Settings.Default.DefaultSMSWriteSend && Properties.Settings.Default.DefaultSMSReadDelete == Properties.Settings.Default.DefaultSMSReceiver && Properties.Settings.Default.DefaultSMSReadDelete == "SM")
                {
                    menuCfgSMSAllSim.Checked = true;
                    menuCfgSMSAllPhone.Checked = false;
                }
                if (Properties.Settings.Default.DefaultSMSReadDelete == Properties.Settings.Default.DefaultSMSWriteSend && Properties.Settings.Default.DefaultSMSReadDelete == Properties.Settings.Default.DefaultSMSReceiver && Properties.Settings.Default.DefaultSMSReadDelete == "ME")
                {
                    menuCfgSMSAllSim.Checked = false;
                    menuCfgSMSAllPhone.Checked = true;
                }
            }

            menuToolsCharSetGSM.Enabled = false;
            menuToolsCharSetHEX.Enabled = false;
            menuToolsCharSetIRA.Enabled = false;
            menuToolsCharSetISO88591.Enabled = false;
            menuToolsCharSetP437.Enabled = false;
            menuToolsCharSetUCS2.Enabled = false;

            menuToolsCharSetGSM.Checked = false;
            menuToolsCharSetHEX.Checked = false;
            menuToolsCharSetIRA.Checked = false;
            menuToolsCharSetISO88591.Checked = false;
            menuToolsCharSetP437.Checked = false;
            menuToolsCharSetUCS2.Checked = false;

            if (SharedLib.ModemGSM.ModelATCommands.CharSetsCMD && SharedLib.ModemGSM.Online)
            {
                foreach (var item in SharedLib.ModemGSM.ValidCharset)
                {
                    if (item == "IRA")
                    {
                        menuToolsCharSetIRA.Enabled = true;
                    }
                    else if (item == "GSM")
                    {
                        menuToolsCharSetGSM.Enabled = true;
                    }
                    else if (item == "HEX")
                    {
                        menuToolsCharSetHEX.Enabled = true;
                    }
                    else if (item == "PCCP437")
                    {
                        menuToolsCharSetP437.Enabled = true;
                    }
                    else if (item == "8859-1")
                    {
                        menuToolsCharSetISO88591.Enabled = true;
                    }
                    else if (item == "UCS2")
                    {
                        menuToolsCharSetUCS2.Enabled = true;
                    }
                }
            }
            ShowMenuToolCharSet();
        }

        private void ShowModemConfig()
        {
            StatusBarModel.Text = SharedLib.ModemGSM.Model;
            StringBuilder status = new StringBuilder();
            if (SharedLib.ModemConfig.PortTested == "" || !SharedLib.ModemConfig.IsTested)
            {
                status.Append("COM??");
            }
            else
            {
                status.Append(SharedLib.ModemGSM.PortName);
            }
            status.Append(",");
            status.Append(SharedLib.ModemGSM.BaudRate.ToString());
            status.Append(",");
            status.Append(SharedLib.ModemGSM.DataBits.ToString());
            status.Append(",");
            switch (SharedLib.ModemGSM.StopBits)
            {
            case System.IO.Ports.StopBits.None:
                status.Append("0");
                break;
            case System.IO.Ports.StopBits.One:
                status.Append("1");
                break;
            case System.IO.Ports.StopBits.OnePointFive:
                status.Append("1.5");
                break;
            case System.IO.Ports.StopBits.Two:
                status.Append("2");
                break;
            }
            StatusBarModemStatus.Text = status.ToString();
            TrayIconMenuModem.Text = status.ToString();
        }
     
        private void ReadContactsLive(bool Silent)
        {

            if (!SharedLib.ModemGSM.IsOpen) return;
            if (SharedLib.LiveIsLogin || (Properties.Settings.Default.DefaultLiveSaveUser && Properties.Settings.Default.DefaultLiveSavePwd && Properties.Settings.Default.DefaultLiveUser != "" && Properties.Settings.Default.DefaultLivePwd != ""))
            {
                string id = SharedLib.ShowTaskWaitVisible(ResourcesText.connectingLive + "...");
                SharedLib.LiveOpeEnv = new LiveOperatingEnvironment();
               
                try
                {
                    if (SharedLib.LiveIsLogin)
                    {
                        SharedLib.LiveOpeEnv.Connect(new System.Net.NetworkCredential(SharedLib.LiveUser, SharedLib.LivePwd), new LiveItemAccessOptions());
                    }
                    else
                    {
                        SharedLib.LiveOpeEnv.Connect(new System.Net.NetworkCredential(Properties.Settings.Default.DefaultLiveUser, SharedLib.Decrypt(Properties.Settings.Default.DefaultLivePwd)), new LiveItemAccessOptions());
                        SharedLib.LiveUser = Properties.Settings.Default.DefaultLiveUser;
                        SharedLib.LivePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultLivePwd);
                        SharedLib.LiveIsLogin = true;
                    }
                }
                catch
                {
                    SharedLib.LiveIsLogin = false;
                    SharedLib.LiveUser = "";
                    SharedLib.LivePwd = "";
                }
                Taskbar.Notifier.Hide(id);
                if (SharedLib.LiveIsLogin)
                {
                    SharedLib.ReadPhoneBookFileName(PhoneStorageEnum.Live, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.LiveUser));
                    FrmBookSync frm = new FrmBookSync();
                    frm.SilentMode = Silent;
                    frm.TypeSync = BookSyncEnum.Live;
                    frm.ShowDialog();
                    SharedLib.SaveLiveBookFileName(PhoneStorageEnum.Live, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.LiveUser));
                }
            }
            else
            { 
                if (SharedLib.LiveUser  != "")
                {
                    SharedLib.ReadPhoneBookFileName(PhoneStorageEnum.Live, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.LiveUser));
                }
            }
        }

        private void ReadContactsGoogle(bool Silent)
        {
            if (!SharedLib.ModemGSM.IsOpen) return;
            if (SharedLib.GoogleIsLogin || (Properties.Settings.Default.DefaultGoogleSaveUser && Properties.Settings.Default.DefaultGoogleSavePwd && Properties.Settings.Default.DefaultGoogleUser != "" && Properties.Settings.Default.DefaultGooglePwd != ""))
            {
                SharedLib.Googleservice = new ContactsService(SharedLib.AssemblyProduct);
                try
                {
                    string id = SharedLib.ShowTaskWaitVisible(ResourcesText.connectingGoogle);
                    if (SharedLib.GoogleIsLogin)
                    {
                        SharedLib.Googleservice.setUserCredentials(SharedLib.GoogleUser, SharedLib.GooglePwd);
                        ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                        query.NumberToRetrieve = 1;
                        SharedLib.Googleservice.Query(query);
                    }
                    else
                    {
                        SharedLib.Googleservice.setUserCredentials(Properties.Settings.Default.DefaultGoogleUser, SharedLib.Decrypt(Properties.Settings.Default.DefaultGooglePwd));
                        ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                        query.NumberToRetrieve = 1;
                        SharedLib.Googleservice.Query(query);
                        SharedLib.GoogleIsLogin = true;
                        SharedLib.GoogleUser = Properties.Settings.Default.DefaultGoogleUser;
                        SharedLib.GooglePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultGooglePwd);
                    }
                    Taskbar.Notifier.Hide(id);
                }
                catch
                {
                    SharedLib.GoogleIsLogin = false;
                    SharedLib.GoogleUser = "";
                    SharedLib.GooglePwd = "";
                }
                if (SharedLib.GoogleIsLogin)
                {
                    SharedLib.ReadPhoneBookFileName(PhoneStorageEnum.Goolgle, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.GoogleUser));
                    FrmBookSync frm = new FrmBookSync();
                    frm.SilentMode = Silent;
                    frm.TypeSync = BookSyncEnum.Goolgle;
                    frm.ShowDialog();
                    SharedLib.SaveLiveBookFileName(PhoneStorageEnum.Goolgle, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.GoogleUser));
                }
                else
                {
                    if (SharedLib.GoogleUser != "")
                    {
                        SharedLib.ReadPhoneBookFileName(PhoneStorageEnum.Goolgle, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.GoogleUser));
                    }
                }
            }
        }
        
        private void SetMenuDefaultValues()
        {
            menuAppAutoDetect.Checked = Properties.Settings.Default.DefaultAutoDetect;
            menuToolsCharSetGSM.Checked = (menuToolsCharSetGSM.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
            menuToolsCharSetHEX.Checked = (menuToolsCharSetHEX.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
            menuToolsCharSetIRA.Checked = (menuToolsCharSetIRA.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
            menuToolsCharSetISO88591.Checked = (menuToolsCharSetISO88591.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
            menuToolsCharSetP437.Checked = (menuToolsCharSetP437.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
            menuToolsCharSetUCS2.Checked = (menuToolsCharSetUCS2.Tag.ToString() == Properties.Settings.Default.DefaultCharSet);
            menuCfgSMSReadDeletePhone.Checked = (Properties.Settings.Default.DefaultSMSReadDelete.ToUpper() == "PHONE");
            menuCfgSMSReadDeleteSim.Checked = (Properties.Settings.Default.DefaultSMSReadDelete.ToUpper() == "SIM");
            menuCfgSMSReceiverPhone.Checked = (Properties.Settings.Default.DefaultSMSReceiver.ToUpper() == "PHONE");
            menuCfgSMSReceiverSim.Checked = (Properties.Settings.Default.DefaultSMSReceiver.ToUpper() == "SIM");
            menuCfgSMSWriteSendPhone.Checked = (Properties.Settings.Default.DefaultSMSWriteSend.ToUpper() == "PHONE");
            menuCfgSMSWriteSendSim.Checked = (Properties.Settings.Default.DefaultSMSWriteSend.ToUpper() == "SIM");
            SharedLib.LiveIsLogin = false;
            SharedLib.LiveUser = Properties.Settings.Default.DefaultLiveUser;
            SharedLib.LivePwd =  SharedLib.Decrypt(Properties.Settings.Default.DefaultLivePwd);
            SharedLib.GoogleIsLogin = false;
            SharedLib.GoogleUser = Properties.Settings.Default.DefaultGoogleUser;
            SharedLib.GooglePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultLivePwd);
        }
        
        private void Startup(bool First,bool ForceConnect)
        {
            ShowLanguage();
            object[] objValues = new object[8];
            objValues[0] = Convert.ToString("Resources.SimCardYellow.ico");
            objValues[1] = Convert.ToString("Resources.SimCardYellow1.ico");
            objValues[2] = Convert.ToString("Resources.SimCardYellow2.ico");
            objValues[3] = Convert.ToString("Resources.SimCardYellow3.ico");
            objValues[4] = Convert.ToString("Resources.SimCardYellow4.ico");
            objValues[5] = Convert.ToString("Resources.SimCardYellow5.ico");
            objValues[6] = Convert.ToString("Resources.SimCardYellow6.ico");
            objValues[7] = Convert.ToString("Resources.SimCardYellow7.ico");
            AppTrayIcon.SetIconRange(this.GetType(), objValues);
            AppTrayIcon.StartAnimation();
            timerStatus.Stop();
            timerStatus.Interval = 50;

            if (SharedLib.ReloadWithLanguage == "")
            {
                SharedLib.ShowoldNewSync = 0;

                SharedLib.LiveContacts.Clear();
                SharedLib.GoogleContacts.Clear();

                SharedLib.LiveIsLogin = false;
                SharedLib.LiveUser = "";
                SharedLib.LivePwd = "";
                Properties.Settings.Default.DefaultLiveUser = "";
                Properties.Settings.Default.DefaultLivePwd = "";
                Properties.Settings.Default.DefaultLiveSavePwd = false;
                Properties.Settings.Default.DefaultLiveSaveUser = true;
                SharedLib.GoogleIsLogin = false;
                SharedLib.GoogleUser = "";
                SharedLib.GooglePwd = "";
                Properties.Settings.Default.DefaultGoogleUser = "";
                Properties.Settings.Default.DefaultGooglePwd = "";
                Properties.Settings.Default.DefaultGoogleSavePwd = false;
                Properties.Settings.Default.DefaultGoogleSaveUser = true;

                Properties.Settings.Default.DefaultPhoneM1Name = "";
                Properties.Settings.Default.DefaultPhoneM1Number = "";
                Properties.Settings.Default.DefaultPhoneM2Name = "";
                Properties.Settings.Default.DefaultPhoneM2Number = "";
                Properties.Settings.Default.DefaultPhoneM3Name = "";
                Properties.Settings.Default.DefaultPhoneM3Number = "";
                Properties.Settings.Default.DefaultPhoneMDDD = "";
            }

            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();

            toolBarStatus.Text = ActiveStatusEnum.Disconnected.ToString();
            toolBarSignal.Text = "";
            toolBarSignal.Image = Properties.Resources.Signal0;
            TrayIconMenuSignal.Image = Properties.Resources.Signal0;
            TrayIconMenuSignal.Text = ResourcesText.SignalQuality;

            toolBarBattery.Image = Properties.Resources.BatMet0;
            TrayIconMenuBattery.Image = Properties.Resources.BatMet0;
            toolBarBattery.Text = "";

            StatusBarModel.Text = "";
            TrayIconMenuModel.Text = ResourcesText.WordModel + " ???";

            StatusBarModemStatus.Text = "";
            TrayIconMenuModem.Text = "COM ??...";


            StatusBarMsg.Text = "";
            StatusBarProgress.Minimum = 0;
            StatusBarProgress.Maximum = 100;
            StatusBarProgress.Value = 0;
            StatusBarProgress.Visible = false;

            if (Properties.Settings.Default.LastSerial != "")
            {
                string nameser = SharedLib.CreateNameModemConfig(Properties.Settings.Default.LastSerial);
                if (!SharedLib.ExistUserFileName(nameser))
                {
                    Properties.Settings.Default.LastSerial = "";
                    Properties.Settings.Default.Save();
                    string Err = ResourcesText.ERRLASTPORTEMPTY;
                    StatusBarMsg.Text = Err;
                    AppTrayIcon.StopAnimation();
                    AppTrayIcon.Icon = iconOFF;
                    SharedLib.ShowTaskNotif(Err);
                    return;
                }
            }
            if (Properties.Settings.Default.LastSerial == "")
            {
                AppTrayIcon.StopAnimation();
                if (!this.Visible)
                {
                    this.WindowState = FormWindowState.Maximized;
                    this.Show();
                }
                FrmModemSet frm = new FrmModemSet();
                frm.Owner = this;
                frm.PerformAutoDect = true;
                frm.PerformConect = false;
                SharedLib.ModemConfig = new DefaultModem();
                frm.ShowDialog();
                if (!SharedLib.ModemConfig.IsTested)
                {
                    StatusBarMsg.Text = SharedLib.ModemGSM.Error;
                    return;
                }
                Properties.Settings.Default.LastSerial = SharedLib.ModemConfig.Serial;
                Properties.Settings.Default.Save();
                string nameser = SharedLib.CreateNameModemConfig(Properties.Settings.Default.LastSerial);
                SharedLib.SaveModemFileName(SharedLib.ModemConfig, nameser);
            }

            string filename = SharedLib.CreateNameModemConfig(Properties.Settings.Default.LastSerial);
            SharedLib.ModemConfig = SharedLib.ReadModemFileName(filename);
            ShowModemConfig();

            filename = SharedLib.CreateNameDefaultSettings(Properties.Settings.Default.LastSerial);
            DefaultSeetings defset = SharedLib.LoadDefaultSeetingsFileName(filename, Properties.Settings.Default.LastSerial);
            SharedLib.SaveDefaultSeetingsFileName(defset, filename);

            filename = SharedLib.CreateNameRegisterPhone(Properties.Settings.Default.LastSerial);
            if (SharedLib.ExistUserFileName(filename))
            {
                SharedLib.ModemGSM.SetValidsAtCommand(SharedLib.ReadRegisterPhoneFileName(filename));
            }

            if (SharedLib.ReloadWithLanguage == "")
            {
                StatusBarMsg.Text = ResourcesText.Tryingopen + " " + SharedLib.ModemConfig.PortTested + " ...";
                SharedLib.ModemGSM.Close();

                SharedLib.ModemGSM.BaudRate = SharedLib.ModemConfig.BaudRate;
                SharedLib.ModemGSM.DataBits = SharedLib.ModemConfig.DataBits;
                SharedLib.ModemGSM.Handshake = SharedLib.ModemConfig.Handshake;
                SharedLib.ModemGSM.OpenTimeOut = SharedLib.ModemConfig.OpenTimeOut;
                SharedLib.ModemGSM.PortName = SharedLib.ModemConfig.PortTested;
                SharedLib.ModemGSM.ReadTimeout = SharedLib.ModemConfig.ReadTimeout;
                SharedLib.ModemGSM.StopBits = SharedLib.ModemConfig.StopBits;
                SharedLib.ModemGSM.WriteTimeout = SharedLib.ModemConfig.WriteTimeout;
                SharedLib.ModemGSM.Open();
            }

            SharedLib.ModemGSM.KeepAlive();

            if (!SharedLib.ModemGSM.Online)
            {
                string Err = ResourcesText.ERROFFLINE;
                StatusBarMsg.Text = Err;
                if (this.Visible)
                {
                    SharedLib.MsgErro(Err);
                }
                SharedLib.ModemGSM.Close();
                AppTrayIcon.StopAnimation();
                AppTrayIcon.Icon = iconOFF;
                if (!this.Visible)
                {
                    SharedLib.ShowTaskNotif(Err);
                }
            }

            if (SharedLib.ModemGSM.Online && SharedLib.ReloadWithLanguage == "")
            {
                if (!SharedLib.ModemGSM.ModemIsPhone())
                {
                    string Err = ResourcesText.ERRNOTGSM;
                    StatusBarMsg.Text = Err;
                    if (this.Visible)
                    {
                        SharedLib.MsgErro(Err);
                    }
                    StatusBarMsg.Text = SharedLib.ModemGSM.Error;
                    SharedLib.ModemGSM.Close();
                    AppTrayIcon.StopAnimation();
                    AppTrayIcon.Icon = iconOFF;
                    if (!this.Visible)
                    {
                        SharedLib.ShowTaskNotif(Err);
                    }
                    return;
                }
                if (SharedLib.ModemGSM.IMEI != SharedLib.ModemConfig.Serial)
                {
                    string Err = ResourcesText.ERRCHGSERIAL;
                    StatusBarMsg.Text = Err;
                    if (this.Visible)
                    {
                        SharedLib.MsgErro(Err);
                    }
                    SharedLib.ModemGSM.Close();
                    AppTrayIcon.StopAnimation();
                    AppTrayIcon.Icon = iconOFF;
                    if (!this.Visible)
                    {
                        SharedLib.ShowTaskNotif(Err);
                    }
                    return;
                }
                filename = SharedLib.CreateNameRegisterPhone(SharedLib.ModemGSM.IMEI);
                if (!SharedLib.ExistUserFileName(filename))
                {
                    if (!this.Visible)
                    {
                        this.WindowState = FormWindowState.Maximized;
                        this.Show();
                    }
                    frmAnalyze frmreg = new frmAnalyze();
                    frmreg.Owner = this;
                    frmreg.ShowDialog();
                    if (!SharedLib.ExistUserFileName(filename))
                    {
                        string Err = ResourcesText.ERRREGISTER;
                        StatusBarMsg.Text = Err;
                        if (this.Visible)
                        {
                            SharedLib.MsgErro(Err);
                        }
                        Properties.Settings.Default.LastSerial = "";
                        Properties.Settings.Default.Save();
                        SharedLib.ModemGSM.Close();
                        StatusBarMsg.Text = Err;
                        AppTrayIcon.StopAnimation();
                        AppTrayIcon.Icon = iconOFF;
                        if (!this.Visible)
                        {
                            SharedLib.ShowTaskNotif(Err);
                        }
                        return;
                    }
                    filename = SharedLib.CreateNameRegisterPhone(SharedLib.ModemGSM.IMEI);
                    SharedLib.ModemGSM.SetValidsAtCommand(SharedLib.ReadRegisterPhoneFileName(filename));
                }
            }

            SharedLib.LiveUser = Properties.Settings.Default.DefaultLiveUser;
            SharedLib.LivePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultLivePwd);
            SharedLib.GoogleUser = Properties.Settings.Default.DefaultGoogleUser;
            SharedLib.GooglePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultGooglePwd);
            if (SharedLib.ReloadWithLanguage == "")
            {
                SharedLib.LiveIsLogin = false;
                SharedLib.GoogleIsLogin = false;
            }
       

            SetMenuDefaultValues();

            ShowModemConfig();

            if (First && menuAppAutoDetect.Checked == false && !ForceConnect && SharedLib.ReloadWithLanguage == "")
            {
                SharedLib.ShowMsgApp("");
                SharedLib.ModemGSM.Close();
                AppTrayIcon.StopAnimation();
                AppTrayIcon.Icon = iconOFF;
                if (!this.Visible)
                {
                    SharedLib.ShowTaskNotif(ResourcesText.ALERTNOTCONNECT);
                }
                return;
            }

            if (SharedLib.ModemGSM.Online && SharedLib.ModemGSM.ModelATCommands.CharSetsCMD)
            {
                SharedLib.ModemGSM.CharSetWrite(Properties.Settings.Default.DefaultCharSet);
            }

            if (SharedLib.ModemGSM.Online && SharedLib.ModemGSM.ModelATCommands.SMSWriteMessageStorageCMD)
            {
                string rd = Properties.Settings.Default.DefaultSMSReadDelete;
                string ws = Properties.Settings.Default.DefaultSMSWriteSend;
                string rc = Properties.Settings.Default.DefaultSMSReceiver;
                SharedLib.SaveSettings();
                SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            }

            if (SharedLib.ModemGSM.Online && SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD)
            {
                SharedLib.ModemGSM.SMSReadExistTextFormat();
                SharedLib.ModemGSM.SMSReadExistPDUFormat();
            }

            if (SharedLib.ModemGSM.Online && SharedLib.ReloadWithLanguage == "")
            {
                filename = SharedLib.CreateNameReport(Properties.Settings.Default.LastSerial);
                SharedLib.ModemGSM.SMSClearStatusReport();
                if (SharedLib.ModemGSM.ModelATCommands.SMSSendMessageCMD)
                {
                    SharedLib.ModemGSM.SMSAddRangeStatusReport(SharedLib.ReadReportFileName(filename).ToArray());
                }
                ShowReportCount();
                SharedLib.SaveReportFileName(SharedLib.ModemGSM.SMSStatusReport, filename);
            }

            SharedLib.ShowMsgApp("");

            SharedLib.ReadInfoModem = true;
            SharedLib.FirstRun = true;
            timerStatus.Interval = 50;
            timerStatus.Start();
        }

        #endregion

        #region Modem Events

        private void ModemGSM_IncomingCallDetected(object sender, RingEventArgs e)
        {
            if (SharedLib.IsWaitIncomingCall)
            {
                return;
            }
            SharedLib.IsWaitIncomingCall = true;
            SharedLib.NameIncomingCall = "";
            SharedLib.NumberIncomingCall = e.Number;
            if (e.Number == "")
            {
                SharedLib.NumberIncomingCall = ResourcesText.RestrictNumber;
                SharedLib.NameIncomingCall = ResourcesText.NotStorage;
            }
            else
            {
                PhoneBook pb = SharedLib.FindPhoneByNumber(e.Number, true);
                if (pb == null)
                {
                    pb = SharedLib.FindPhoneByNumber(e.Number, false);
                }
                if (pb == null)
                {
                    string Number = e.Number;
                    if (Number.Length >= Properties.Settings.Default.DefaultCodeOper.Length)
                    {
                        string code = Properties.Settings.Default.DefaultCodeOper.ToUpper().Replace("X", "");
                        if (Number.StartsWith(code))
                        {
                            Number = Number.Substring(Properties.Settings.Default.DefaultCodeOper.Length);
                        }
                        pb = SharedLib.FindPhoneByNumber(Number, true);
                        if (pb == null)
                        {
                            pb = SharedLib.FindPhoneByNumber(Number, false);
                        }
                    }
                }
                if (pb != null)
                {
                    SharedLib.NameIncomingCall = pb.Name;
                }
                else
                {
                    SharedLib.NameIncomingCall = ResourcesText.NotStorage;
                }
            }
            if (AsynIncomingCall != null)
            {
                if (AsynIncomingCall.IsAlive)
                {
                    AsynIncomingCall.Abort();
                }
            }
            AsynIncomingCall = new Thread(GetIncomingCall);
            AsynIncomingCall.Start(this);
        }

        private void ModemGSM_SMSReport(object sender, SmsReportEventArgs e)
        {
            switch (e.Report.TypeReport)
            {
                case TypeStatusReportEnum.SendConfirmation:
                    SharedLib.QtdNewSMSReport++;
                    StatusSMSReport result = SharedLib.ModemGSM.SMSFindStatusReportByNumber(e.Report.Number);
                    if (result != null)
                    {
                        SharedLib.ModemGSM.SMSRemoveStatusReport(result);
                        result.DateTimeReceiver = e.Report.DateTimeReceiver;
                        result.Status = e.Report.Status;
                        result.TimezoneReceiver = e.Report.TimezoneReceiver;
                        SharedLib.ModemGSM.SMSAddStatusReport(result);
                        string FileName = SharedLib.CreateNameReport(SharedLib.ModemGSM.IMEI);
                        SharedLib.SaveReportFileName(SharedLib.ModemGSM.SMSStatusReport, FileName);
                    }
                    break;
                case TypeStatusReportEnum.ReceiverAlert:
                    {
                        SharedLib.ReadInfoSMS = true;
                        SharedLib.QtdNewSMSMessage++;
                    }
                    break;
            }
        }

        #endregion 

        #region Timer Events

        private void timerSMSBlink_Tick(object sender, EventArgs e)
        {
            _blink = !_blink;
            if (SharedLib.QtdNewSMSMessage + SharedLib.QtdNewSMSReport == 0)
            {
                toolBarSMS.Image = Properties.Resources.SMS;
                toolBarSMSRelat.Image = Properties.Resources.relat;
                timerSMSBlink.Stop();
            }
            if (SharedLib.QtdNewSMSMessage == 0)
            {
                toolBarSMS.Image = Properties.Resources.SMS;
            }
            if (SharedLib.QtdNewSMSReport == 0)
            {
                toolBarSMSRelat.Image = Properties.Resources.relat;
            }
            if (_blink)
            {
                if (SharedLib.QtdNewSMSMessage != 0)
                {
                    toolBarSMS.Image = Properties.Resources.SMS;
                }
                if (SharedLib.QtdNewSMSReport != 0)
                {
                    toolBarSMSRelat.Image = Properties.Resources.relat;
                }
            }
            else
            {
                if (SharedLib.QtdNewSMSMessage != 0)
                {
                    toolBarSMS.Image = Properties.Resources.SMS_OFF;
                }
                if (SharedLib.QtdNewSMSReport != 0)
                {
                    toolBarSMSRelat.Image = Properties.Resources.relat_OFF;
                }
            }
        }

        private void timerStatus_Tick(object sender, EventArgs e)
        {
            if (!SharedLib.ReadInfoModem && timerStatus.Interval != 1000)
            {
                timerStatus.Interval = 1000;
            }
            ShowToolBarStatus();
            timerStatus.Stop();
            switch (SharedLib.ModemGSM.ActiveStatus)
            {
                case ActiveStatusEnum.Busy:
                case ActiveStatusEnum.NoDialtone:
                case ActiveStatusEnum.NoCarrier:
                case ActiveStatusEnum.NoAnswer:
                case ActiveStatusEnum.Ringing:
                case ActiveStatusEnum.call:
                    {
                        SharedLib.ModemGSM.ReadActiveStatus();
                        timerStatus.Interval = 500;
                        timerStatus.Start();
                        return;
                    }
            }
            if (!SharedLib.ModemGSM.IsOpen && menuAppAutoDetect.Checked == false)
            {
                return;
            }
            if (AsyncStatusModem == null)
            {
                AsyncStatusModem = new Thread(GetStatusModem);
            }
            if (AsyncStatusModem.IsAlive)
            {
                timerStatus.Interval = 500;
                timerStatus.Start();
                return;
            }
            if (SharedLib.RunningWaitProcessThread)
            {
                timerStatus.Interval = 500;
                timerStatus.Start();
                return;
            }
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();

            if (!SharedLib.FirstRun)
            {

                SharedLib.PollingCountModem++;
                if (SharedLib.ModemGSM.Online)
                {
                    SharedLib.PollingCountLive++;
                    SharedLib.PollingCountGoogle++;
                    SharedLib.PollingCountSMS++;
                }

                if (SharedLib.PollingCountGoogle == _PollingIntervalGoogle)
                {
                    SharedLib.PollingCountGoogle = 0;
                    SharedLib.ReadInfoGoogle = true;
                }
                if (SharedLib.PollingCountLive == _PollingIntervalLive)
                {
                    SharedLib.PollingCountLive = 0;
                    SharedLib.ReadInfoLive = true;
                }
                if (SharedLib.PollingCountSMS == _PollingIntervalSMS)
                {
                    SharedLib.PollingCountSMS = 0;
                    SharedLib.ReadInfoSMS = true;
                }
                if (!SharedLib.ModemGSM.Online)
                {
                    if (SharedLib.CountOffLine == 0)
                    {
                        RefreshStatusModem();
                    }
                    int Fator = 1;
                    if (SharedLib.CountOffLine < 5)
                    {
                        Fator = 1;
                    }
                    else if (SharedLib.CountOffLine >= 5 && SharedLib.CountOffLine <= 10 )
                    {
                        Fator = 2;
                    }
                    else if (SharedLib.CountOffLine >= 10 && SharedLib.CountOffLine <= 20)
                    {
                        Fator = 4;
                    }
                    else if (SharedLib.CountOffLine > 20 && SharedLib.CountOffLine <= 30)
                    {
                        Fator = 8;
                    }
                    else if (SharedLib.CountOffLine > 30 && SharedLib.CountOffLine <= 50)
                    {
                        Fator = 16;
                    }
                    else if (SharedLib.CountOffLine > 50)
                    {
                        SharedLib.CountOffLine = 0;
                        Fator = 1;
                    }
                    if (SharedLib.PollingCountModem >= (_PollingIntervalModem * Fator))
                    {
                        SharedLib.CountOffLine++;
                        SharedLib.PollingCountModem = 0;
                        AsyncStatusModem = new Thread(GetStatusModem);
                        StatusBarMsg.Text = ResourcesText.Tryingopen + " " + SharedLib.ModemConfig.PortTested + " ...";
                        SharedLib.ReadInfoModem = true;
                        AsyncStatusModem.Start(this);
                    }
                    timerStatus.Start();
                    return;
                }
                SharedLib.CountOffLine = 0;
                RefreshStatusModem();
                if (SharedLib.ReadInfoSMS || SharedLib.ReadInfoLive || SharedLib.ReadInfoGoogle || SharedLib.PollingCountModem >= _PollingIntervalModem)
                {
                    switch (SharedLib.ModemGSM.ActiveStatus)
                    {
                        case ActiveStatusEnum.Unavailable:
                        case ActiveStatusEnum.Disconnected:
                        case ActiveStatusEnum.unknown:
                        case ActiveStatusEnum.Offline:
                        case ActiveStatusEnum.Error:
                        case ActiveStatusEnum.asleep:
                            SharedLib.ReadInfoModem = true;
                            break;
                        case ActiveStatusEnum.Ready:
                            SharedLib.ReadInfoModem = false;
                            break;
                    }
                    if (SharedLib.SaveReport)
                    {
                        string FileName = SharedLib.CreateNameReport(SharedLib.ModemGSM.IMEI);
                        SharedLib.SaveReportFileName(SharedLib.ModemGSM.SMSStatusReport, FileName);
                        SharedLib.SaveReport = false;
                    }
                    SharedLib.PollingCountModem = 0;
                    if (SharedLib.ReadInfoSMS)
                    {
                        ShowSMSMessageCount();
                    }
                    AsyncStatusModem = new Thread(GetStatusModem);
                    AsyncStatusModem.Start(this);
                }
            }
            else
            {
                if (SharedLib.ReloadWithLanguage == "")
                {
                    SharedLib.ReadInfoModem = true;
                    SharedLib.ReadInfoLive = true;
                    SharedLib.ReadInfoGoogle = true;
                    SharedLib.ReadInfoSMS = true;
                    this.Cursor = Cursors.WaitCursor;
                    if (SharedLib.ModemGSM.Online)
                    {
                        GetStatusModem(this);
                    }
                    AppTrayIcon.StopAnimation();
                    if (SharedLib.ReloadWithLanguage == "")
                    {
                        if (SharedLib.ReloadWithLanguage == "")
                            AppTrayIcon.Icon = iconOFF;
                            if (SharedLib.ModemGSM.Online)
                            {
                                AppTrayIcon.Icon = iconON;
                                SharedLib.ShowTaskNotif(SharedLib.ModemGSM.Model + " " + ResourcesText.isConnected);
                            }
                    }
                    SharedLib.FirstRun = false;
                }
                AppTrayIcon.StopAnimation();
                SharedLib.FirstRun = false;
                ShowAllStatusModem();
                SharedLib.ReloadWithLanguage = "";
                this.Cursor = Cursors.Default;
            }
            if (SharedLib.QtdNewSMSMessage + SharedLib.QtdNewSMSReport != 0)
            {
                timerSMSBlink.Start();
            }
            timerStatus.Start();
        }

        #endregion

        #region Form Events

        private bool _StartHide = false;
        public MDIPhoneManager(string loc)
        {
            Properties.Settings.Default.LastLng = loc;
            Properties.Settings.Default.Save();
            SharedLib.CultureUI = new CultureInfo(loc);

            Thread.CurrentThread.CurrentCulture = SharedLib.CultureUI;
            Thread.CurrentThread.CurrentUICulture = SharedLib.CultureUI;

            InitializeComponent();

            _StartHide = false;

            iconON = new Icon(GetType(), "Resources.SimCardGreen.ico");
            iconOFF = new Icon(GetType(), "Resources.SimCardRed.ico");

            CreateTrayMenu();
        }

        public MDIPhoneManager()
        {
            if (Properties.Settings.Default.LastLng == "")
            {
                Properties.Settings.Default.LastLng = Thread.CurrentThread.CurrentUICulture.Name;
                Properties.Settings.Default.Save();

            }

            SharedLib.CultureUI = new CultureInfo(Properties.Settings.Default.LastLng);

            Thread.CurrentThread.CurrentCulture = SharedLib.CultureUI;
            Thread.CurrentThread.CurrentUICulture = SharedLib.CultureUI;


            InitializeComponent();

            if (Properties.Settings.Default.LastSerial != "")
            {
                _StartHide = true;
            }

            iconON = new Icon(GetType(), "Resources.SimCardGreen.ico");
            iconOFF = new Icon(GetType(), "Resources.SimCardRed.ico");

            CreateTrayMenu();
        }

        private void MDIPhoneManager_Load(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.ModemGSM.IncomingCallDetected += new Modem.RingDetectEventHandler(ModemGSM_IncomingCallDetected);
            SharedLib.ModemGSM.SMSReport += new Modem.SmsReportEventHandler(ModemGSM_SMSReport);
            _PollingIntervalModem = Properties.Settings.Default.DefaultPollingModem;
            _PollingIntervalLive = Properties.Settings.Default.DefaultPollingLive;
            _PollingIntervalGoogle = Properties.Settings.Default.DefaultPollingGoogle;
            _PollingIntervalSMS = Properties.Settings.Default.DefaultPollingSMS;
            if (SharedLib.ReloadWithLanguage == "")
            {
                SharedLib.PollingCountModem = 0;
                SharedLib.PollingCountLive = 0;
                SharedLib.PollingCountGoogle = 0;
                SharedLib.PollingCountSMS = 0;
            }
            this.Text = SharedLib.AssemblyTitle + " " + SharedLib.AssemblyVersion;
            if (Properties.Settings.Default.HideMenu)
            {
                menuMdi.Visible = false;
                toolBarpin.Visible = true;
                toolBar.Dock = DockStyle.Top;
            }
            else
            {
                menuMdi.Visible = true;
                toolBarpin.Visible = false;
                toolBar.Dock = DockStyle.Bottom;
            }

        }

        private void MDIPhoneManager_Shown(object sender, EventArgs e)
        {
            if (_StartHide)
            {
                this.Hide();
            }
            else
            {

                this.WindowState = FormWindowState.Maximized;
            }

            this.Cursor = Cursors.WaitCursor;
            StatusBarModel.Text = "";
            Startup(true, false);
            this.Cursor = Cursors.Default;
        }

        private void menuAppConnect_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();
            Startup(true,true);
            this.Cursor = Cursors.Default;
        }

        private bool _ThisClose = false;
        private void menuAppExit_Click(object sender, EventArgs e)
        {
            _ThisClose = true;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            AppTrayIcon.Dispose();
            Taskbar.Notifier.HideAll();
            this.Close();
        }

        private void toolBarListOperators_Click(object sender, EventArgs e)
        {
            menuToolsListOper.PerformClick();
        }

        private void menuHelpAbout_Click(object sender, EventArgs e)
        {
            AboutBox frm = new AboutBox();
            frm.Owner = SharedLib.MainForm;
            frm.ShowDialog();
        }

        private void menuToolsListOper_Click(object sender, EventArgs e)
        {
            FrmProviders frm = new FrmProviders();
            frm.Owner = SharedLib.MainForm;
            frm.ShowDialog();
        }

        private void menuToolsModem_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            FrmModemSet frm = new FrmModemSet();
            frm.PerformConect = false;
            frm.PerformAutoDect = false;
            frm.Owner = this;
            SharedLib.ModemConfig = new DefaultModem();
            frm.ShowDialog();
            if (SharedLib.ModemConfig.IsTested)
            {
                Properties.Settings.Default.LastSerial = SharedLib.ModemConfig.Serial;
                SharedLib.SaveSettings();
                string nameser = SharedLib.CreateNameModemConfig(Properties.Settings.Default.LastSerial);
                SharedLib.SaveModemFileName(SharedLib.ModemConfig, nameser);
            }
            ShowAllStatusModem();
            Startup(true,true);
        }

        private void menuAppDisconnect_Click(object sender, EventArgs e)
        {
            SharedLib.PhoneManagerStartup = false;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ShowMsgApp(ResourcesText.WordDisconnecting + "...");
            SharedLib.ModemGSM.Close();
            SharedLib.LiveContacts.Clear();
            SharedLib.GoogleContacts.Clear();
            SharedLib.ShowMsgApp("");
            ShowAllStatusModem();
        }

        private void menuPhoneAlarms_Click(object sender, EventArgs e)
        {
            FrmAlarms frm = new FrmAlarms();
            frm.Owner = SharedLib.MainForm;
            frm.ShowDialog();
        }

        private void toolBarAlarms_Click(object sender, EventArgs e)
        {
            menuPhoneAlarms.PerformClick();
        }

        private void menuSyncDateTime_Click(object sender, EventArgs e)
        {
            FrmClock frm = new FrmClock();
            frm.Owner = SharedLib.MainForm;
            frm.ShowDialog();
        }

        private void toolBarSyncDateTime_Click(object sender, EventArgs e)
        {
            menuSyncDateTime.PerformClick();
        }

        private void menuAppAutoDetect_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.DefaultAutoDetect = menuAppAutoDetect.Checked;
            SharedLib.SaveSettings();
        }

        private void menuToolsCharSetIRA_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ModemGSM.CharSetWrite(menuToolsCharSetIRA.Tag.ToString());
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            if (SharedLib.ModemGSM.Error == "")
            {
                Properties.Settings.Default.DefaultCharSet = menuToolsCharSetIRA.Tag.ToString();
                SharedLib.SaveSettings();
            }
            ShowMenuToolCharSet();
            timerStatus.Start();
        }

        private void menuToolsCharSetGSM_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ModemGSM.CharSetWrite(menuToolsCharSetGSM.Tag.ToString());
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            if (SharedLib.ModemGSM.Error == "")
            {
                Properties.Settings.Default.DefaultCharSet = menuToolsCharSetGSM.Tag.ToString();
                SharedLib.SaveSettings();
            }
            ShowMenuToolCharSet();
            timerStatus.Start();
        }

        private void menuToolsCharSetHEX_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ModemGSM.CharSetWrite(menuToolsCharSetHEX.Tag.ToString());
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            if (SharedLib.ModemGSM.Error == "")
            {
                Properties.Settings.Default.DefaultCharSet = menuToolsCharSetHEX.Tag.ToString();
                SharedLib.SaveSettings();
            }
            ShowMenuToolCharSet();
            timerStatus.Start();
        }

        private void menuToolsCharSetP437_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ModemGSM.CharSetWrite(menuToolsCharSetP437.Tag.ToString());
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            if (SharedLib.ModemGSM.Error == "")
            {
                Properties.Settings.Default.DefaultCharSet = menuToolsCharSetP437.Tag.ToString();
                SharedLib.SaveSettings();
            }
            ShowMenuToolCharSet();
            timerStatus.Start();
        }

        private void menuToolsCharSetISO88591_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ModemGSM.CharSetWrite(menuToolsCharSetISO88591.Tag.ToString());
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            if (SharedLib.ModemGSM.Error == "")
            {
                Properties.Settings.Default.DefaultCharSet = menuToolsCharSetISO88591.Tag.ToString();
                SharedLib.SaveSettings();
            }
            ShowMenuToolCharSet();
            timerStatus.Start();
        }

        private void menuToolsCharSetUCS2_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ModemGSM.CharSetWrite(menuToolsCharSetUCS2.Tag.ToString());
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            if (SharedLib.ModemGSM.Error == "")
            {
                Properties.Settings.Default.DefaultCharSet = menuToolsCharSetUCS2.Tag.ToString();
                SharedLib.SaveSettings();
            }
            ShowMenuToolCharSet();
            timerStatus.Start();
        }

        private void menuSyncLiveLoginLogOff_Click(object sender, EventArgs e)
        {
            FrmLiveGoogleLogin frm = new FrmLiveGoogleLogin();
            SharedLib.LiveUser = Properties.Settings.Default.DefaultLiveUser;
            SharedLib.LivePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultLivePwd);
            frm.Owner = SharedLib.MainForm;
            frm.User = SharedLib.LiveUser;
            frm.Pwd = SharedLib.LivePwd;
            frm.TypeLogin = PhoneStorageEnum.Live;
            frm.SaveUser = Properties.Settings.Default.DefaultLiveSaveUser;
            frm.SavePwd = Properties.Settings.Default.DefaultLiveSavePwd;
            frm.ShowDialog();
            if (SharedLib.LiveIsLogin)
            {
                this.Cursor = Cursors.WaitCursor;
                timerStatus.Stop();
                SharedLib.StartWaitProcessThread();
                timerStatus.Interval = 50;
                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
                SharedLib.ReadPhoneBook();
                SharedLib.ShowMsgApp("");
                SharedLib.EndWaitProcessThread();
                if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
                {
                    this.Cursor = Cursors.Default;
                    SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                }
                else
                {
                    SharedLib.ReadPhoneBookFileName(PhoneStorageEnum.Live, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.LiveUser));
                    FrmBookSync frmSync = new FrmBookSync();
                    frmSync.SilentMode = true;
                    frmSync.TypeSync = BookSyncEnum.Live;
                    frmSync.ShowDialog();
                    ShowPhonebookCount();
                    ShowSyncLiveGoogle();
                    SharedLib.SaveLiveBookFileName(PhoneStorageEnum.Live, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.LiveUser));
                    SharedLib.PollingCountLive = 0;
                }
                this.Cursor = Cursors.Default;

                toolBarSyncLive.Image = Properties.Resources.live;
                menuSyncLive.Image = Properties.Resources.live;
                menuSyncLiveLoginLogOff.Text = ResourcesText.Logout;
                toolBarSyncLiveLoginLogOff.Text = ResourcesText.Logout;
                menuSyncLivePhone.Enabled = true;
                toolBarSyncLivePhone.Enabled = true;
                timerStatus.Start();

            }
            else
            {
                toolBarSyncLive.Image = Properties.Resources.liveOff;
                menuSyncLive.Image = Properties.Resources.liveOff;
                menuSyncLiveLoginLogOff.Text = ResourcesText.Login;
                toolBarSyncLiveLoginLogOff.Text = ResourcesText.Login;
                menuSyncLivePhone.Enabled = false;
                toolBarSyncLivePhone.Enabled = false;
            }
        }

        private void toolBarSyncLiveLoginLogOff_Click(object sender, EventArgs e)
        {
            menuSyncLiveLoginLogOff.PerformClick();
        }

        private void menuSyncGoogleLoginLogOff_Click(object sender, EventArgs e)
        {
            FrmLiveGoogleLogin frm = new FrmLiveGoogleLogin();
            SharedLib.GoogleUser = Properties.Settings.Default.DefaultGoogleUser;
            SharedLib.GooglePwd = SharedLib.Decrypt(Properties.Settings.Default.DefaultGooglePwd);
            frm.Owner = SharedLib.MainForm;
            frm.User = SharedLib.GoogleUser;
            frm.Pwd = SharedLib.GooglePwd;
            frm.TypeLogin = PhoneStorageEnum.Goolgle;
            frm.SaveUser = Properties.Settings.Default.DefaultGoogleSaveUser;
            frm.SavePwd = Properties.Settings.Default.DefaultGoogleSavePwd ;
            frm.ShowDialog();
            if (SharedLib.GoogleIsLogin)
            {
                this.Cursor = Cursors.WaitCursor;
                timerStatus.Stop();
                SharedLib.StartWaitProcessThread();
                timerStatus.Interval = 50;
                SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
                SharedLib.ReadPhoneBook();
                SharedLib.ShowMsgApp("");
                SharedLib.EndWaitProcessThread();
                if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
                {
                    this.Cursor = Cursors.Default;
                    SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                }
                else
                {
                    SharedLib.ReadPhoneBookFileName(PhoneStorageEnum.Goolgle, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.GoogleUser));
                    FrmBookSync frmSync = new FrmBookSync();
                    frmSync.SilentMode = true;
                    frmSync.TypeSync = BookSyncEnum.Goolgle;
                    frmSync.ShowDialog();
                    SharedLib.SaveLiveBookFileName(PhoneStorageEnum.Goolgle, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.GoogleUser));
                    ShowPhonebookCount();
                    ShowSyncLiveGoogle();
                    SharedLib.PollingCountGoogle = 0;
                }
                this.Cursor = Cursors.Default;

                toolBarSyncGoogle.Image = Properties.Resources.GOOGLE;
                menuSyncGoogle.Image = Properties.Resources.GOOGLE;
                menuSyncGoogleLoginLogOff.Text = ResourcesText.Logout;
                toolBarSyncGoogleLoginLogOff.Text = ResourcesText.Logout;
                menuSyncGooglePhone.Enabled = true;
                toolBarSyncGooglePhone.Enabled = true;
                timerStatus.Start();
            }
            else
            {
                toolBarSyncGoogle.Image = Properties.Resources.GOOGLEOff;
                menuSyncGoogle.Image = Properties.Resources.GOOGLEOff;
                menuSyncGoogleLoginLogOff.Text = ResourcesText.Login;
                toolBarSyncGoogleLoginLogOff.Text = ResourcesText.Login;
                menuSyncGooglePhone.Enabled = false;
                toolBarSyncGooglePhone.Enabled = false;
            }
        }

        private void toolBarSyncGoogleLoginLogOff_Click(object sender, EventArgs e)
        {
            menuSyncGoogleLoginLogOff.PerformClick();
        }

        private void menuSyncLivePhone_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            timerStatus.Interval = 50;
            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
            SharedLib.ReadPhoneBook();
            SharedLib.ShowMsgApp("");
            SharedLib.EndWaitProcessThread();
            this.Cursor = Cursors.WaitCursor;
            if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
            {
                this.Cursor = Cursors.Default;
                SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                timerStatus.Start();
                return;
            }
            ReadContactsLive(false);
            ShowSyncLiveGoogle();
            ShowPhonebookCount();
            this.Cursor = Cursors.Default;
            SharedLib.PollingCountLive = 0;
            timerStatus.Start();
            if (SharedLib.ShowPhoneSync)
            {
                menuPhoneBook.PerformClick();
            }
        }

        private void menuPhoneBook_Click(object sender, EventArgs e)
        {
            Application.DoEvents();
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            timerStatus.Interval = 50;
            this.Cursor = Cursors.WaitCursor;
            bool sync = SharedLib.ShowPhoneSync;
            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
            SharedLib.ReadPhoneBook();
            SharedLib.ShowMsgApp("");
            this.Cursor = Cursors.WaitCursor;
            if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
            {
                this.Cursor = Cursors.Default;
                SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                timerStatus.Start();
                return;
            }
            timerStatus.Start();
            FrmPhoneBook frm = new FrmPhoneBook();
            frm.ShowSync = sync;
            SharedLib.ShowPhoneBook = false;
            SharedLib.ShowPhoneSync = false;
            frm.Owner = SharedLib.MainForm;
            this.Cursor = Cursors.Default;
            frm.ShowDialog();
            ShowSyncLiveGoogle();
            ShowPhonebookCount();
        }

        private void toolBarBook_Click(object sender, EventArgs e)
        {
            menuPhoneBook.PerformClick();
        }

        private void toolBarSyncGooglePhone_Click(object sender, EventArgs e)
        {
            menuSyncGooglePhone.PerformClick();
        }

        private void toolBarSyncLivePhone_Click(object sender, EventArgs e)
        {
            menuSyncLivePhone.PerformClick();
        }

        private void menuSyncGooglePhone_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            timerStatus.Interval = 50;
            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
            SharedLib.ReadPhoneBook();
            SharedLib.ShowMsgApp("");
            SharedLib.EndWaitProcessThread();
            this.Cursor = Cursors.WaitCursor;
            if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
            {
                this.Cursor = Cursors.Default;
                SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                timerStatus.Start();
                return;
            }
            ReadContactsGoogle(false);
            ShowSyncLiveGoogle();
            ShowPhonebookCount();
            SharedLib.PollingCountGoogle = 0;
            timerStatus.Start();
            this.Cursor = Cursors.Default;
            if (SharedLib.ShowPhoneSync)
            {
                menuPhoneBook.PerformClick();
            }
        }

        private void MDIPhoneManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!_ThisClose)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void menuBookBackup_Click(object sender, EventArgs e)
        {

            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
            SharedLib.ReadPhoneBook();
            ShowPhonebookCount();
            SharedLib.ShowMsgApp("");
            SharedLib.EndWaitProcessThread();
            if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
            {
                SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                timerStatus.Start();
                return;
            }
            FrmBackup frm = new FrmBackup();
            frm.Owner = SharedLib.MainForm;
            frm.ShowDialog();
            timerStatus.Start();
        }

        private void toolBarBookBackup_Click(object sender, EventArgs e)
        {
            menuBookBackup.PerformClick();
        }

        private void menuBookRestore_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
            SharedLib.ReadPhoneBook();
            SharedLib.ShowMsgApp("");
            SharedLib.EndWaitProcessThread();
            if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
            {
                SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                timerStatus.Start();
                return;
            }
            FrmRestore frm = new FrmRestore();
            frm.Owner = this;
            frm.ShowDialog();
            timerStatus.Start();
            if (SharedLib.ShowPhoneBook)
            {
                SharedLib.ShowPhoneBook = false;
                FrmPhoneBook frmpb = new FrmPhoneBook();
                frmpb.Owner = SharedLib.MainForm;
                frmpb.ShowSync = false;
                frmpb.ShowDialog();
            }
            ShowPhonebookCount();
        }

        private void toolBarBookRestore_Click(object sender, EventArgs e)
        {
            menuBookRestore.PerformClick();
        }

        private void menuPhoneTalk_Click(object sender, EventArgs e)
        {
            FrmDial frm = new FrmDial();
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void toolBarTalk_Click(object sender, EventArgs e)
        {
            menuPhoneTalk.PerformClick();
        }

        private void toolBarSMS_Click(object sender, EventArgs e)
        {
            menuSMSSend.PerformClick();
        }

        private void sendMessageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            timerSMSBlink.Stop();
            toolBarSMS.Image = Properties.Resources.SMS;
            SharedLib.QtdNewSMSMessage = 0;

            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            timerStatus.Interval = 50;
            this.Cursor = Cursors.WaitCursor;
            bool sync = SharedLib.ShowPhoneSync;
            SharedLib.ShowMsgApp(ResourcesText.WordReading + " " + ResourcesText.SMSMessages + "...");
            if (SharedLib.ModemGSM.ModelATCommands.SMSListMessageCMD)
            {
                SharedLib.ModemGSM.SMSListMessagesTextFormat();
            }
            ShowSMSMessageCount();
            timerStatus.Start();
            SharedLib.ShowMsgApp("");
            FrmSMS frm = new FrmSMS();
            frm.Owner = this;
            frm.ShowDialog();
            SharedLib.ReadInfoSMS = true;
        }

        private void menuCfgSMSReadDeleteSim_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSReadDeletePhone.Checked  = !menuCfgSMSReadDeleteSim.Checked;
            string rd = "SM";
            if (menuCfgSMSReadDeletePhone.Checked)
            {
                rd = "ME";
            }
            string ws = "SM";
            if (menuCfgSMSWriteSendPhone.Checked)
            {
                ws = "ME";
            }
            string rc = "SM";
            if (menuCfgSMSReceiverPhone.Checked)
            {
                rc = "ME";
            }
            Properties.Settings.Default.DefaultSMSReadDelete = rd;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd,ws,rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (rd == ws && rd == rc && rd == "SM")
            {
                menuCfgSMSAllSim.Checked = true;
                menuCfgSMSAllPhone.Checked = false;
            }
            if (rd == ws && rd == rc && rd == "ME")
            {
                menuCfgSMSAllSim.Checked = false;
                menuCfgSMSAllPhone.Checked = true;
            }
            timerStatus.Start();
        }

        private void menuCfgSMSReadDeletePhone_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSReadDeleteSim.Checked = !menuCfgSMSReadDeletePhone.Checked;
            string rd = "ME";
            if (menuCfgSMSReadDeleteSim.Checked)
            {
                rd = "SM";
            }
            string ws = "ME";
            if (menuCfgSMSWriteSendSim.Checked)
            {
                ws = "SM";
            }
            string rc = "ME";
            if (menuCfgSMSReceiverSim.Checked)
            {
                rc = "SM";
            }
            Properties.Settings.Default.DefaultSMSReadDelete = rd;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (rd == ws && rd == rc && rd == "SM")
            {
                menuCfgSMSAllSim.Checked = true;
                menuCfgSMSAllPhone.Checked = false;
            }
            if (rd == ws && rd == rc && rd == "ME")
            {
                menuCfgSMSAllSim.Checked = false;
                menuCfgSMSAllPhone.Checked = true;
            }
            timerStatus.Start();
        }

        private void menuCfgSMSWriteSendSim_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSWriteSendPhone.Checked = !menuCfgSMSWriteSendSim.Checked;
            string ws = "ME";
            if (menuCfgSMSWriteSendSim.Checked)
            {
                ws = "SM";
            }
            string rd = "ME";
            if (menuCfgSMSReadDeleteSim.Checked)
            {
                rd = "SM";
            }
            string rc = "ME";
            if (menuCfgSMSReceiverSim.Checked)
            {
                rc = "SM";
            }
            Properties.Settings.Default.DefaultSMSWriteSend = ws;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (rd == ws && rd == rc && rd == "SM")
            {
                menuCfgSMSAllSim.Checked = true;
                menuCfgSMSAllPhone.Checked = false;
            }
            if (rd == ws && rd == rc && rd == "ME")
            {
                menuCfgSMSAllSim.Checked = false;
                menuCfgSMSAllPhone.Checked = true;
            }
            timerStatus.Start();
        }

        private void menuCfgSMSWriteSendPhone_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSWriteSendSim.Checked = !menuCfgSMSWriteSendPhone.Checked;
            string ws = "ME";
            if (menuCfgSMSWriteSendSim.Checked)
            {
                ws = "SM";
            }
            string rd = "ME";
            if (menuCfgSMSReadDeleteSim.Checked)
            {
                rd = "SM";
            }
            string rc = "ME";
            if (menuCfgSMSReceiverSim.Checked)
            {
                rc = "SM";
            }
            Properties.Settings.Default.DefaultSMSWriteSend = ws;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (rd == ws && rd == rc && rd == "SM")
            {
                menuCfgSMSAllSim.Checked = true;
                menuCfgSMSAllPhone.Checked = false;
            }
            if (rd == ws && rd == rc && rd == "ME")
            {
                menuCfgSMSAllSim.Checked = false;
                menuCfgSMSAllPhone.Checked = true;
            }
            timerStatus.Start();
        }

        private void menuCfgSMSReceiverSim_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSReceiverPhone.Checked = !menuCfgSMSReceiverSim.Checked;
            string rc = "ME";
            if (menuCfgSMSReceiverSim.Checked)
            {
                rc = "SM";
            }
            string rd = "ME";
            if (menuCfgSMSReadDeleteSim.Checked)
            {
                rd = "SM";
            }
            string ws = "ME";
            if (menuCfgSMSWriteSendSim.Checked)
            {
                ws = "SM";
            }
            Properties.Settings.Default.DefaultSMSReceiver = rc;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (rd == ws && rd == rc && rd == "SM")
            {
                menuCfgSMSAllSim.Checked = true;
                menuCfgSMSAllPhone.Checked = false;
            }
            if (rd == ws && rd == rc && rd == "ME")
            {
                menuCfgSMSAllSim.Checked = false;
                menuCfgSMSAllPhone.Checked = true;
            }
            timerStatus.Start();
        }

        private void menuCfgSMSReceiverPhone_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSReceiverSim.Checked = !menuCfgSMSReceiverPhone.Checked;
            string rc = "ME";
            if (menuCfgSMSReceiverSim.Checked)
            {
                rc = "SM";
            }
            string rd = "ME";
            if (menuCfgSMSReadDeleteSim.Checked)
            {
                rd = "SM";
            }
            string ws = "ME";
            if (menuCfgSMSWriteSendSim.Checked)
            {
                ws = "SM";
            }
            Properties.Settings.Default.DefaultSMSReceiver = rc;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = false;
            if (rd == ws && rd == rc && rd == "SM")
            {
                menuCfgSMSAllSim.Checked = true;
                menuCfgSMSAllPhone.Checked = false;
            }
            if (rd == ws && rd == rc && rd == "ME")
            {
                menuCfgSMSAllSim.Checked = false;
                menuCfgSMSAllPhone.Checked = true;
            }
            timerStatus.Start();
        }

        private void menuToolsAnalizeModem_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            frmAnalyze frm = new frmAnalyze();
            frm.Owner = this;
            frm.ShowDialog();
            string filename = SharedLib.CreateNameRegisterPhone(SharedLib.ModemConfig.Serial);
            SharedLib.ModemGSM.SetValidsAtCommand(SharedLib.ReadRegisterPhoneFileName(filename));
            if (SharedLib.ModemGSM.ModelATCommands.ActiveStatusCMD)
            {
                if (SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD)
                {
                    SharedLib.ModemGSM.SMSReadExistTextFormat();
                    SharedLib.ModemGSM.SMSReadExistPDUFormat();
                }
                else
                {
                    SharedLib.ModemGSM.ExistSMSText = false; 
                    SharedLib.ModemGSM.ExistSMSPDU = false;
                }
            }
            SharedLib.ReadInfoModem = true;
            ShowMenusAndToolbarAction();
            timerStatus.Interval = 50;
            timerStatus.Start();
        }

        private void menuCfgSMSAllSim_Click(object sender, EventArgs e)
        {
            menuCfgSMSAllSim.Checked = true;
            menuCfgSMSAllPhone.Checked = false;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSReadDeletePhone.Checked = false;
            menuCfgSMSWriteSendPhone.Checked = false;
            menuCfgSMSReceiverPhone.Checked = false;
            menuCfgSMSReadDeleteSim.Checked = true;
            menuCfgSMSWriteSendSim.Checked = true;
            menuCfgSMSReceiverSim.Checked = true;

            string rd = "SM";
            string ws = "SM";
            string rc = "SM";
            Properties.Settings.Default.DefaultSMSReadDelete = rd;
            Properties.Settings.Default.DefaultSMSWriteSend = ws;
            Properties.Settings.Default.DefaultSMSReceiver = rc;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            timerStatus.Start();
        }

        private void menuCfgSMSAllPhone_Click(object sender, EventArgs e)
        {
            menuCfgSMSAllSim.Checked = false;
            menuCfgSMSAllPhone.Checked = true;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            menuCfgSMSReadDeletePhone.Checked = true;
            menuCfgSMSWriteSendPhone.Checked = true;
            menuCfgSMSReceiverPhone.Checked = true;
            menuCfgSMSReadDeleteSim.Checked = false;
            menuCfgSMSWriteSendSim.Checked = false;
            menuCfgSMSReceiverSim.Checked = false;

            string rd = "ME";
            string ws = "ME";
            string rc = "ME";
            Properties.Settings.Default.DefaultSMSReadDelete = rd;
            Properties.Settings.Default.DefaultSMSWriteSend = ws;
            Properties.Settings.Default.DefaultSMSReceiver = rc;
            SharedLib.SaveSettings();
            timerStatus.Interval = 50;
            SharedLib.ModemGSM.SMSStoragesWrite(rd, ws, rc);
            SharedLib.ShowMsgApp(SharedLib.ModemGSM.Error);
            timerStatus.Start();
        }

        private void toolBarSMSRelat_Click(object sender, EventArgs e)
        {
            menuSMSReport.PerformClick();
        }

        private void menuSMSReport_Click(object sender, EventArgs e)
        {
            Application.DoEvents();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.QtdNewSMSReport = 0;
            FrmReport frm = new FrmReport();
            frm.Owner = this;
            frm.ShowDialog();
            if (SharedLib.ModemGSM.KeepAlive())
            {
                string FileName = SharedLib.CreateNameReport(SharedLib.ModemGSM.IMEI);
                SharedLib.SaveReportFileName(SharedLib.ModemGSM.SMSStatusReport, FileName);
                SharedLib.SaveReport = false;
            }
            else
            {
                SharedLib.SaveReport = true;
            }
        }

        private void menuToolsDefaultSet_Click(object sender, EventArgs e)
        {
            Application.DoEvents();
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            FrmDefaultSettings frm = new FrmDefaultSettings();
            frm.Owner = this;
            SharedLib.ChangeDefaultSet = false;
            frm.ShowDialog();
            if (!SharedLib.ChangeDefaultSet)
            {
                timerStatus.Start();
            }
            else
            {
                ShowAllStatusModem();
                Startup(false,true);
            }
        }

        private void MDIPhoneManager_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                TrayIconDisabled();
                TrayIconMenuHide.Enabled = true;
                TrayIconMenuShow.Enabled = true;
            }
            else
            {
                TrayIconEnabled();
            }
        }

        private void MDIPhoneManager_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Maximized;
                TrayIconEnabled();
                this.Hide();
            }
        }

        private void menuHelpSeach_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(ResourcesText.URLProject);
        }

        private void MDIPhoneManager_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void MDIPhoneManager_DragDrop(object sender, DragEventArgs e)
        {
            Form frm = (Form)e.Data.GetData(e.Data.GetFormats()[0]);
            frm.Top = e.Y;
            frm.Left = e.X;
        }

        private void menuLng_Click(object sender, EventArgs e)
        {
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            SharedLib.ReloadWithLanguage = ((ToolStripMenuItem)sender).Tag.ToString();
            Properties.Settings.Default.LastLng = SharedLib.ReloadWithLanguage;
            Properties.Settings.Default.Save();
            _ThisClose = true;
            for (int i = 2; i < 10; i++)
            {
                this.Opacity = 1 - (i / 10);
                Thread.Sleep(200);
            }
            this.Close();
        }

        private bool _translate = false;
        private void toolBarStatus_TextChanged(object sender, EventArgs e)
        {
            if (!_translate)
            {
                _translate = true;
                toolBarStatus.Text = SharedLib.TranslateStatus(toolBarStatus.Text);
                _translate = false;
            }
        }



        private void menutoolpin_Click(object sender, EventArgs e)
        {
            menuMdi.Visible = false;
            toolBarpin.Visible = true;
            toolBar.Dock = DockStyle.Top;
            Properties.Settings.Default.HideMenu = true;
            Properties.Settings.Default.Save();
        }

        private void toolBarpin_Click(object sender, EventArgs e)
        {
            toolBarpin.Visible = false;
            toolBar.Dock = DockStyle.Bottom;
            menuMdi.Visible = true;
            Properties.Settings.Default.HideMenu = false;
            Properties.Settings.Default.Save();
        }

        private void toolBarStatus_Click(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.HideMenu)
            {
                menuAppConnect.PerformClick();
            }
        }

        private void menuHelpFaq_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(ResourcesText.UrlFAQ);
        }

        #endregion

        #region Trayicon Menu

        private void ShowTrayIcon()
        {
            if (this.Visible)
            {
                TrayIconMenuConnect.Enabled = false;
                TrayIconMenuPhonebook.Enabled = false;
                TrayIconMenuTalk.Enabled = false;
                TrayIconMenuSMS.Enabled = false;
            }
            else
            {
                TrayIconMenuConnect.Enabled = !SharedLib.ModemGSM.IsOpen;
                TrayIconMenuPhonebook.Enabled = SharedLib.ModemGSM.Online && SharedLib.ModemGSM.ModelATCommands.PhoneBookCMD;
                TrayIconMenuTalk.Enabled = SharedLib.ModemGSM.Online;
                TrayIconMenuSMS.Enabled = SharedLib.ModemGSM.ModelATCommands.SMSFormatCMD && SharedLib.ModemGSM.Online;
            }
        }
        private void ShowLanguage()
        {
            string lng = SharedLib.GetValidLanguage(Thread.CurrentThread.CurrentUICulture.Name);
            menuLanguage.Image = SharedLib.GetImageLanguage(lng);
        }

        private void AppTrayIcon_MouseMove(object sender, MouseEventArgs e)
        {
            if (AppTrayIcon.GetAnimationIconList.Length == 2)
            {
                AppTrayIcon.StopAnimation();
            }
        }

        private void TrayIconExit_Click(Object sender, System.EventArgs e)
        {
            _ThisClose = true;
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            Taskbar.Notifier.HideAll();
            AppTrayIcon.Dispose();
            this.Close();
        }

        private void TrayIconHide_Click(Object sender, System.EventArgs e)
        {
            this.Hide();
        }

        private void TrayIconShow_Click(Object sender, System.EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            this.Show();
            this.TopMost = true;
            this.TopMost = false;
            TrayIconDisabled();
            TrayIconMenuHide.Enabled = true;
            TrayIconMenuShow.Enabled = true;
            AppTrayIcon.Visible = false;
            AppTrayIcon.Visible = true;
            this.Focus();
        }
        
        private void TrayIconDisabled()
        { 
            TrayIconMenuConnect.Enabled = false;
            TrayIconMenuHide.Enabled = false;
            TrayIconMenuPhonebook.Enabled = false;
            TrayIconMenuTalk.Enabled = false;
            TrayIconMenuSMS.Enabled = false;
            TrayIconMenuShow.Enabled = false;
            AppTrayIcon.Visible = false;
            AppTrayIcon.Visible = true;
        }

        private void TrayIconEnabled()
        {
            TrayIconMenuConnect.Enabled = true;
            TrayIconMenuHide.Enabled = true;
            TrayIconMenuPhonebook.Enabled = true;
            TrayIconMenuTalk.Enabled = true;
            TrayIconMenuSMS.Enabled = true;
            TrayIconMenuShow.Enabled = true;
            AppTrayIcon.Visible = false;
            AppTrayIcon.Visible = true;
        }

        private void TrayIconMenuTalk_Click(object sender, EventArgs e)
        {
            TrayIconDisabled();
            FrmDial frm = new FrmDial();
            frm.TopMost = true;
            frm.StartPosition = FormStartPosition.CenterScreen;
            AppTrayIcon.Visible = false;
            AppTrayIcon.Visible = true;
            frm.ShowDialog();
            TrayIconEnabled();
        }

        private void TrayIconMenuPhonebook_Click(object sender, EventArgs e)
        {
            TrayIconDisabled();
            Application.DoEvents();
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            timerStatus.Interval = 50;
            this.Cursor = Cursors.WaitCursor;
            bool sync = SharedLib.ShowPhoneSync;
            string id = SharedLib.ShowTaskWaitVisible(ResourcesText.WordReading + " " + ResourcesText.Phonebook + "...");
            SharedLib.ReadPhoneBook();
            Taskbar.Notifier.Hide(id);
            this.Cursor = Cursors.WaitCursor;
            if (!SharedLib.PhoneBookReadSIMOK || !SharedLib.PhoneBookReadMEMOK)
            {
                this.Cursor = Cursors.Default;
                SharedLib.MsgErro(ResourcesText.NotReadPBatSto);
                timerStatus.Start();
                TrayIconEnabled();
                return;
            }
            timerStatus.Start();
            FrmPhoneBook frm = new FrmPhoneBook();
            frm.ShowSync = sync;
            SharedLib.ShowPhoneBook = false;
            SharedLib.ShowPhoneSync = false;
            frm.TopMost = true;
            frm.StartPosition = FormStartPosition.CenterScreen;
            this.Cursor = Cursors.Default;
            AppTrayIcon.Visible = false;
            AppTrayIcon.Visible = true;
            frm.ShowDialog();
            TrayIconEnabled();
            ShowSyncLiveGoogle();
            ShowPhonebookCount();
        }

        private void TrayIconMenuSMS_Click(object sender, EventArgs e)
        {
            TrayIconDisabled();
            timerStatus.Stop();
            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            timerSMSBlink.Stop();
            toolBarSMS.Image = Properties.Resources.SMS;
            SharedLib.QtdNewSMSMessage = 0;

            SharedLib.StartWaitProcessThread();
            SharedLib.EndWaitProcessThread();
            timerStatus.Interval = 50;
            this.Cursor = Cursors.WaitCursor;
            string id = SharedLib.ShowTaskWaitVisible(ResourcesText.WordReading + " " + ResourcesText.SMSMessages + "...");
            if (SharedLib.ModemGSM.ModelATCommands.SMSListMessageCMD)
            {
                SharedLib.ModemGSM.SMSListMessagesTextFormat();
            }
            ShowSMSMessageCount();
            Taskbar.Notifier.Hide(id);
            timerStatus.Start();
            SharedLib.ShowMsgApp("");
            FrmSMS frm = new FrmSMS();
            frm.TopMost = true;
            frm.StartPosition = FormStartPosition.CenterScreen;
            AppTrayIcon.Visible = false;
            AppTrayIcon.Visible = true;
            frm.ShowDialog();
            SharedLib.ReadInfoSMS = true;
            TrayIconEnabled();
        }

        private void TrayIconMenuConnect_Click(object sender, EventArgs e)
        {
            menuAppConnect.PerformClick();
        }

        #endregion


    }
}
